php處理非同步請求 PHP非同步請求實現方式

2021-10-22 23:04:56 字數 3087 閱讀 3811

一.使用fsockopen的方式

我們建立了乙個基於fsockopen的函式,這個函式中利用fsockopen去訪問url,但是在訪問時,並不要求獲取url顯示的內容,而是僅僅發出訪問請求,請求到達後馬上關閉這個訪問.

* 使用fsocketopen()方式傳送非同步請求,put方式

stream_set_blocking($fp,true);//開啟了手冊上說的非阻塞模式

//如果傳遞引數在body中,則使用

//usleep(1000); // 這一句也是關鍵,如果沒有這延時,可能在nginx伺服器上就無法執行成功

$result = "";

//獲取返回結果, 如果不迴圈接收返回值,請求發出後直接關閉連線, 則為非同步請求

while(!feof($fp)) {

$result .= fgets($fp, 1024);

//print_r($result);

fclose($fp);

呼叫方式:

echo date("y-m-d h:i:s").'-----'.time()."

";$url = '';

$param = [

'id'=>10,

'userid'=>2,

'name'=>'zhangsan'

//使用fsocketopen方式實現非同步請求

$this->syncrequest($url,"",json_encode($param));

echo date("y-m-d h:i:s").'-----'.time()."

";二.使用php的curl擴充套件

curl實現方式的本質是, 設定超時時間為1秒或者n毫秒;

注意: 如果設定超時時間為毫秒,那麼要確認,curl版本》=7.16.2, php 版本》=5.2.3.

* 使用curl方式傳送非同步請求, put方式

public function _curl($url,$params) {

$ch = curl_init();

"cache-control: no-cache","pragma: no-cache");

curl_setopt($ch, curlopt_customrequest,"put"); //設定請求方式

curl_setopt($ch, curlopt_postfields, $params);//設定提交的字串

curl_setopt($ch, curlopt_httpheader, $headers); //設定頭資訊

curl_setopt($ch, curlopt_url, $url); // 要訪問的位址

curl_setopt($ch, curlopt_returntransfer , 1 ); //獲取的資訊以檔案流的形式返回

curl_setopt($ch, curlopt_ssl_verifypeer, false); //不進行ssl驗證

curl_setopt($ch, curlopt_autoreferer, 1); // 自動設定referer

//設定超時時間為1秒,超過1秒則關閉連線

curl_setopt($ch,curlopt_timeout,1);

//curl_setopt($ch, curlopt_nosignal, 1); //注意,毫秒超時一定要設定這個

//curl_setopt($ch, curlopt_timeout_ms, 200); //超時毫秒,curl 7.16.2中被加入。從php 5.2.3起可使用

curl_setopt($ch, curlopt_header, 0); // 設定是否顯示返回頭資訊 1返回 0不返回

curl_setopt($ch, curlopt_nobody, 0); //不想在輸出中包含body部分,設定這個選項為乙個非零值

$result = curl_exec($ch);

curl_close($ch);

return json_decode($result);

呼叫方式:

echo date("y-m-d h:i:s").'-----'.time()."

";$url = '';

$param = [

'id'=>10,

'userid'=>2,

'name'=>'zhangsan'

//使用curl方式實現非同步請求,超時時間設定為1秒

$this->_curl($url,json_encode($param));

echo date("y-m-d h:i:s").'-----'.time()."

";

php處理非同步請求 PHP實現非同步呼叫方法研究

瀏覽器和伺服器之間是通過 http 協議進行連線通訊的。這是一種基於請求和響應模型的協議。瀏覽器通過 url 向伺服器發起請求,web 伺服器接收到請求,執行一段程式,然後做出響應,傳送相應的html 給客戶端。這就有了乙個問題,web 伺服器執行一段程式,可能幾毫秒就完成,也可能幾分鐘都完不成。如...

php非同步處理

namespace index controller usecore controller class test extends controller public function test12 php非同步請求 param host string 主機位址 param path string 路...

php 非同步執行

header host url array host r n http 1.1 host域不能省略 header connection close r n r n header connection close r n r n if empty post data out connection cl...