<?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;
}
?>
11 回答
当请求方法时,它将具有
array
. 所以只需查看count()
即可 .3v4l.org/U51TE
通过使用
示例
有关详细信息,请参阅documentation for the $_SERVER variable .
由于这是关于REST,仅从服务器获取请求方法是不够的 . 您还需要接收RESTful路由参数 . 分离RESTful参数和GET / POST / PUT参数的原因是资源需要有自己唯一的URL用于标识 .
这是使用Slim在PHP中实现RESTful路由的一种方法:
https://github.com/codeguy/Slim
并相应地配置服务器 .
这是使用AltoRouter的另一个例子:
https://github.com/dannyvankooten/AltoRouter
通过这种方式,您还可以在zend框架2中实现 . 谢谢 .
可以使用以下代码片段来检测HTTP方法或所谓的
REQUEST METHOD
.如果你喜欢
if-else
语句,你也可以使用switch
来做 .如果html表单中需要
GET
或POST
以外的方法,则通常使用表单中的隐藏字段来解决此问题 .有关HTTP方法的更多信息,我想参考以下StackOverflow问题:
HTTP protocol's PUT and DELETE and their usage in PHP
PHP中的REST可以非常简单地完成 . 创建http://example.com/test.php(概述如下) . 将此用于REST调用,例如http://example.com/test.php/testing/123/hello . 这适用于Apache和Lighttpd开箱即用,不需要重写规则 .
Example:
您可以使用
getenv
函数,而不必使用$_SERVER
变量:更多信息:
http://php.net/manual/en/function.getenv.php
我们还可以使用input_filter来检测请求方法,同时还通过输入卫生提供安全性 .
你可以得到任何查询字符串数据,即
www.example.com?id=2&name=r
您必须使用
$_GET['id']
或$_REQUEST['id']
获取数据 .发布数据意味着形式
<form action='' method='POST'>
您必须使用$_POST
或$_REQUEST
.在核心php中你可以这样做: