1. 程式人生 > >php非同步實現,避免長時間等待

php非同步實現,避免長時間等待

處理的php非同步的方法有好幾種,這裡我就只介紹我經常用的而且官方也推薦的

廢話少說,直接貼程式碼

//php非同步
    public function doRequest($host,$path, $param=array()){
        $query = isset($param)? http_build_query($param) : ''; 

        $port = 80; 
        $errno = 0; 
        $errstr = ''; 
        $timeout = 10; 

        $fp = fsockopen($host, $port, $errno, $errstr, $timeout); 

        $out = "POST ".$path." HTTP/1.1\r\n"; 
        $out .= "host:".$host."\r\n"; 
        $out .= "content-length:".strlen($query)."\r\n"; 
        $out .= "content-type:application/x-www-form-urlencoded\r\n"; 
        $out .= "connection:close\r\n\r\n"; 
        $out .= $query; 

        fputs($fp, $out);
        fclose($fp); 
    }
    
    //呼叫例項:(我這裡值介紹POST方式,GET方便那麼簡單就不介紹了,一樣的)
    //引數說明:引數1[請求目標地址的主域名],引數2[路勁,一般是"入口檔案/模組/控制器/操作方法",當然也不排除你的單個php檔案訪問,後面就是你要進行傳遞的資料了了]
    public function ybutest(){
        $this->doRequest('www.cms.com','/api.php/User/Users/login',array(
            'username'=>'test001',
            'pwd'=>'123456',
            'service_type'=>1,
            'call_back_rul'=>'http://www.dbtool.com/index.php/Home/Index/test_write',
            )
        );
    }