接收用的主程式:
- 註解裡面的程式主要是通過 curl 指令模擬提交
- PUT/DELETE 需要通過訊息流得到
- 另外標準的 PUT/DELETE 會在檔頭(headers)當中含有 HTTP_X_HTTP_METHOD_OVERRIDE
- 程式中使用了 PHP5.3 才有的 ?: 三元運算符 (New Ternary Operator)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class RESTful {
const IS_GET = "get";
const IS_POST = "post";
const IS_PUT = "put";
const IS_DELETE = "delete";
public static function get($key, $default_value = "") {
return $_GET[$key] ?: $default_value;
}
public static function post($key, $default_value = "") {
return $_POST[$key] ?: $default_value;
}
public static function method() {
return $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ?: $_SERVER['REQUEST_METHOD'];
}
public static function data($key = "", $default_value = "") {
$method = strtolower(self::method());
switch($method) {
case self::IS_GET:
case self::IS_POST:
return self::$method($key, $default_value);
break;
case self::IS_PUT:
case self::IS_DELETE:
return file_get_contents('php://input');
break;
}
}
}
echo RESTful::method()."\n";
/*
* GET : curl -G -d "text=123" "http://localhost/test/php-restful/index.php"
* POST: curl -d "text=123" "http://localhost/test/php-restful/index.php"
*/
echo RESTful::data("text")."\n";
/*
* PUT : curl -X PUT -d "text=123" http://localhost/test/php-restful/index.php
* DELETE: curl -X DELETE -d "text=123" http://localhost/test/php-restful/index.php
*/
echo RESTful::data()."\n";