在我们PHP开发工作中可能会碰到需要通过Curl的方式传递指定的参数调用接口来获取数据的情况,而在我们编写接口的过程中接受传递过来的参数会根据传递的数据方式有关,下面是我工作中碰到的一些情况,主要是post提交数据的方式。
- 我们创建一个post.php文件,内容如下
/** * HTTP请求(支持HTTP/HTTPS,支持GET/POST) * @param $url 请求url地址 * @param null $data post数据 * @param int $timeout * @return mixed */ function http_request($url, $data=null, $timeout=0){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if(!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); if ($timeout > 0) { //超时时间秒 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout); } $output = curl_exec($curl); $error = curl_errno($curl); curl_close($curl); if($error){ return false; } return $output; } //json格式的方式投递参数 echo http_request('localhost/index.php',json_encode(array('name'=>'aaa','age'=>25))); //字符格式的方式投递参数 echo http_request('localhost/index.php','name=aaa&age=25'); //数组格式的方式投递参数 echo http_request('localhost/index.php',array('name'=>'aaa','age'=>25));
- 创建一个接受参数信息的文件indxe.php,内容如下:
echo json_encode($_POST);exit; echo file_get_contents('php://input');exit;
通过测试我们发现:
1、以字符和数组格式投递参数的时候,只能使用$_POST的方式接受参数
2、以json格式投递的参数,只能使用file_get_contents('php://input')的方式接受参数;
下面是测试时的截图: