php使用curl模拟post请求

废话很少说,直接上代码,作个笔记。php

$url="http://localhost/header_server.php"; $body = array("mobile"=>"13899999999", "username"=>"Nick"); $header = array("Content-Type:multipart/x-www-form-urlencoded", "token:test", "client:h5");
$result = curlPost($url, $body, 5, $header, 'json'); var_dump($result); /** * 传入数组进行HTTP POST请求 */
function curlPost($url, $post_data = array(), $timeout = 5, $header = "", $data_type = "") { $header = empty($header) ? '' : $header; //支持json数据数据提交
    if($data_type == 'json'){ $post_string = json_encode($post_data); }elseif($data_type == 'array') { $post_string = $post_data; }elseif(is_array($post_data)){ $post_string = http_build_query($post_data, '', '&'); } $ch = curl_init();    // 启动一个CURL会话
    curl_setopt($ch, CURLOPT_URL, $url);     // 要访问的地址
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查 // https请求 不验证证书和hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 //curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);     // Post提交的数据包
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);     // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); //curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
    $result = curl_exec($ch); // 打印请求的header信息 //$a = curl_getinfo($ch); //var_dump($a);
 curl_close($ch); return $result; }

 几点经验:算法

1. 无论"Content-Type:multipart/form-data"仍是"Content-Type:application/x-www-form-urlencoded"只要采用post方式发送数据,而且在body体中的数据是数组格式,那么在接收端就可使用$_POST获取到。
2. 在接收端使用file_get_contents("php://input")接收时,只能获取到字符串类型的body体数据。
3. 请求时,在header中添加的参数xxx,在接收端可使用$_SERVER["HTTP_XXX"]进行获取。
相关文章
相关标签/搜索