request.php源码
<?php # GET/POST var_dump($_REQUEST); #PHP数据流 $input = file_get_contents('php://input'); var_dump($input); #上传文档 var_dump($_FILES);
传递请求数据
默认curl使用GET方式请求数据,这种方式下直接通过URL传递数据
可以通过 --data/-d 方式指定使用POST方式传递数据
# GET curl http://172.20.41.35:82/conf/cc/request.php?access_token=XXXXXXXXXX
结果: array(1) { ["access_token"]=> string(10) "XXXXXXXXXX" } string(0) "" array(0) { }
# POST curl --data "param1=value1¶m2=value2" http://172.20.41.35:82/conf/cc/request.php
结果: array(2) { ["param1"]=> string(6) "value1" ["param2"]=> string(5) "value2" } string(26) "param1=value1¶m2=value2" array(0) { }
# POST JSON curl --data "{"param1":"value1","param2":"value2"}" http://172.20.41.35:82/conf/cc/request.php curl --connect-timeout 15 -H "Content-Type: application/json" -sd '{"data":"value"}' http://172.20.41.35:82/conf/cc/request.php
结果: array(0) { } string(29) "{param1:value1,param2:value2}" array(0) { }
# POST XML curl --data "<?xml version="1.0" encoding="utf-8" ?> <Root> <user id="001"> <admin> <name>yucai</name> <password>123456</password> <age>21</age> </admin> </user> </Root>" http://172.20.41.35:82/conf/cc/request.php
结果: array(1) { ["<?xml_version"]=> string(171) "1.0 encoding=utf-8 ?> <Root> <user id=001> <admin> <name>yucai</name> <password>123456</password> <age>21</age> </admin> </user> </Root>" } string(185) "<?xml version=1.0 encoding=utf-8 ?> <Root> <user id=001> <admin> <name>yucai</name> <password>123456</password> <age>21</age> </admin> </user> </Root>" array(0) { }
file.txt内容
# 也可以指定一个文件,将该文件中的内容当作数据传递给服务器端 curl --data @file.txt http://172.20.41.35:82/conf/cc/request.php
结果: array(0) { } string(2) "11" array(0) { }
注:默认情况下,通过POST方式传递过去的数据中若有特殊字符,首先需要将特殊字符转义在传递给服务器端,如value值中包含有空格,则需要先将空格转换成%20,如:
curl -d "value%201"
结果: array(0) { } string(9) "value%201" array(0) { }
在新版本的CURL中,提供了新的选项 --data-urlencode,通过该选项提供的参数会自动转义特殊字符。
curl --data-urlencode "value 1"
结果: array(0) { } string(9) "value%201" array(0) { }
除了使用GET和POST协议外,还可以通过 -X 选项指定其它协议,如:
curl -I -X DELETE
结果: HTTP/1.1 200 OK Date: Tue, 30 Sep 2014 02:36:40 GMT Server: Apache/2.2.8 (Win32) PHP/5.2.6 X-Powered-By: PHP/5.2.6 Content-Length: 26 Content-Type: text/html
上传文件
curl --form "[email protected]" http://172.20.41.35:82/conf/cc/request.php
结果: array(0) { } string(0) "" array(1) { ["fileupload"]=> array(5) { ["name"]=> string(8) "file.txt" ["type"]=> string(10) "text/plain" ["tmp_name"]=> string(27) "C:\Windows\Temp\php65E1.tmp" ["error"]=> int(0) ["size"]=> int(3) } }