Home  >  Article  >  Backend Development  >  PHP中模拟处理HTTP PUT请求的例子_PHP

PHP中模拟处理HTTP PUT请求的例子_PHP

WBOY
WBOYOriginal
2016-06-01 11:50:23754browse

关于HTTP PUT详细介绍请参阅此文:http://www.bitsCN.com/article/52515.htm。

PHP里有$_GET,$_POST,但是没有$_PUT,所以如果需要使用它的话,则你不得不自己模拟一下:

代码如下:


 $_PUT = array();
if ('PUT' == $_SERVER['REQUEST_METHOD']) {
     parse_str(file_get_contents('php://input'), $_PUT);
 }

通过php://input得到的数据是raw data,所以需要用parse_str解析一下。

不过需要说明的是,当表单是enctype="multipart/form-data"类型的时候(就是上传文件那种类型),这种方法是无效的(此时 php://input为空),一旦PHP发现请求的Content-Type是multipart/form-data,就会无条件的代你处理表单数据,然后保存到$_FILES里,此时无法得到raw data,只能用一些偏门方法

以apache为例,修改httpd.conf(为了使用RequestHeader语法,请先激活header模块):

代码如下:



     RequestHeader set Content-Type foobar


通过重置Content-Type请求头为foobar(只要不是multipart/form-data即可),此时php://input就有数据了,不过原本应有的$_FILES数据却不存在了,所以基本上只有演示上的意义,如果想得到raw data,只能自己根据数据生成,在PEAR里有类似的实现:HTTP_Request2_MultipartBody。

浏览器一般只允许使用GET/POST方法,虽然可以通过JS来发送PUT方法,但是还得编写代码,相对而言,使用命令行下的CURL命令则显得方便很多,在开发测试时很有用,所以学习一下还是必要的:

代码如下:


curl -X PUT http://www.domain.com/demo.php -d "id=1" -d "title=a"


这样就会通过PUT方法发送id, title数据,测试时demo.php的代码就类似上面的php://input。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn