php 模擬post 請求
阿新 • • 發佈:2022-05-24
$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;
}