我怎么能检测到哪个请求类型被使用(GET, POST, PUT或删除)在PHP?
当前回答
在core php中,你可以这样做:
<?php
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
//Here Handle GET Request
echo 'You are using '.$method.' Method';
break;
case 'POST':
//Here Handle POST Request
echo 'You are using '.$method.' Method';
break;
case 'PUT':
//Here Handle PUT Request
echo 'You are using '.$method.' Method';
break;
case 'PATCH':
//Here Handle PATCH Request
echo 'You are using '.$method.' Method';
break;
case 'DELETE':
//Here Handle DELETE Request
echo 'You are using '.$method.' Method';
break;
case 'COPY':
//Here Handle COPY Request
echo 'You are using '.$method.' Method';
break;
case 'OPTIONS':
//Here Handle OPTIONS Request
echo 'You are using '.$method.' Method';
break;
case 'LINK':
//Here Handle LINK Request
echo 'You are using '.$method.' Method';
break;
case 'UNLINK':
//Here Handle UNLINK Request
echo 'You are using '.$method.' Method';
break;
case 'PURGE':
//Here Handle PURGE Request
echo 'You are using '.$method.' Method';
break;
case 'LOCK':
//Here Handle LOCK Request
echo 'You are using '.$method.' Method';
break;
case 'UNLOCK':
//Here Handle UNLOCK Request
echo 'You are using '.$method.' Method';
break;
case 'PROPFIND':
//Here Handle PROPFIND Request
echo 'You are using '.$method.' Method';
break;
case 'VIEW':
//Here Handle VIEW Request
echo 'You are using '.$method.' Method';
break;
Default:
echo 'You are using '.$method.' Method';
break;
}
?>
其他回答
我们还可以使用input_filter来检测请求方法,同时通过输入环境保护来提供安全性。
$request = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);
通过使用
$_SERVER['REQUEST_METHOD']
例子
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request is using the POST method
}
要了解更多细节,请参阅$_SERVER变量的文档。
当一个方法被请求时,它将有一个数组。因此,只需使用count()进行检查。
$m=['GET'=>$_GET,'POST'=>$_POST];
foreach($m as$k=>$v){
echo count($v)?
$k.' was requested.':null;
}
3 v4l.org/u51te
你可以使用getenv函数,而不必使用$_SERVER变量:
getenv('REQUEST_METHOD');
更多信息:
http://php.net/manual/en/function.getenv.php
PHP中的REST可以非常简单地实现。创建http://example.com/test.php(如下所示)。将此用于REST调用,例如http://example.com/test.php/testing/123/hello。这与Apache和Lighttpd一起开箱即用,不需要重写规则。
<?php
$method = $_SERVER['REQUEST_METHOD'];
$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
switch ($method) {
case 'PUT':
do_something_with_put($request);
break;
case 'POST':
do_something_with_post($request);
break;
case 'GET':
do_something_with_get($request);
break;
default:
handle_error($request);
break;
}
推荐文章
- 原则-如何打印出真正的sql,而不仅仅是准备好的语句?
- 如何从关联PHP数组中获得第一项?
- PHP/MySQL插入一行然后获取id
- 我如何排序一个多维数组在PHP
- 如何在PHP中截断字符串最接近于一定数量的字符?
- PHP错误:“zip扩展名和unzip命令都没有,跳过。”
- Nginx提供下载。php文件,而不是执行它们
- Json_encode()转义正斜杠
- 如何在PHP中捕获cURL错误
- 如何要求一个分叉与作曲家?
- 如何在php中创建可选参数?
- 在文本文件中创建或写入/追加
- 为什么PHP的json_encode函数转换UTF-8字符串为十六进制实体?
- 如何从一个查询插入多行使用雄辩/流利
- 在PHP单元测试执行期间,如何在CLI中输出?