PHP 發送異步請求, post請求

* 異步執行方法

* string $url 地址

* array? $post_data 參數

*/

public functiontrigger_async_request($url,$post_data=array())

{

$method=empty($post_data) ?"GET":"POST";

$url_array= parse_url($url);

$port=isset($url_array['port']) ?$url_array['port'] :80;

$fp= fsockopen($url_array['host'],$port,$errno,$errstr,30);

if(!$fp) {

return false;// 無法打開socket連接

}

$getPath=isset($url_array['query']) ?$url_array['path'] ."?".$url_array['query'] :$url_array['path'];

$header=$method." ".$getPath." HTTP/1.1\r\n";

$header.="Host: ".$url_array['host'] ."\r\n";

if(!empty($post_data)) {

$post_data= http_build_query($post_data);

$header.="Content-Type: application/x-www-form-urlencoded\r\n";

$header.="Content-Length: ". strlen($post_data) ."\r\n";

}

$header.="Connection: Close\r\n\r\n";

if(!empty($post_data)) {

$header.=$post_data."\r\n\r\n";//傳遞POST數據

}

fwrite($fp,$header);

// 等待30ms,這對于nginx服務器很重要,讓nginx有足夠的時間將請求轉交給php-fpm。

// 否則,如果在nginx轉交請求前識別到用戶斷開連接,那么就不會繼續轉交請求了。

//? ? ? ? usleep(30000);

fclose($fp);

return true;

}




/**

* 請求

*/

public function https_curl_json($url,$data,$type){

if($type=='json'){//json $_POST=json_decode(file_get_contents('php://input'), TRUE);

$headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");

$data=json_encode($data);

}

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_POST, 1); // 發送一個常規的Post請求

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, 1);

curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );

$output = curl_exec($curl);

if (curl_errno($curl)) {

echo 'Errno'.curl_error($curl);//捕抓異常

}

curl_close($curl);

return $output;

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容