Home  >  Article  >  Backend Development  >  Asynchronous execution of PHP task fsockopen

Asynchronous execution of PHP task fsockopen

coldplay.xixi
coldplay.xixiforward
2020-06-08 11:28:372346browse

Asynchronous execution of PHP task fsockopen

Practical method of PHP asynchronously executing the task fsockopen

We created a function based on fsockopen. In this function Use fsockopen to access the url, but when accessing, it is not required to obtain the content displayed in the url, but only issues an access request, and the access is closed immediately after the request arrives.

The advantage of this is that there is no need to wait for the visited URL to return reliable information, which saves time. The execution time of this code is between 0.1-0.2 seconds. For ordinary visitors, it is almost Not noticeable. Therefore, when using it, you only need to call this function and the corresponding url. However, there is no data transmission part provided here. How to transmit data, in fact, you only need to add the post content to $header.

/**
 * @生生 2018/12/24 19:25:06
 * [asynchronous PHP异步执行任务]
 * @param  string $url       执行任务的url地址
 * @param  array  $post_data 需要post提交的数据POST
 * @param  array  $cookie    cookie数据用于登录等的设置(此处内部调用,无需鉴权)
 * @return boole
 */
public function asynchronous($url,$post_data = array())
{
    $url_array = parse_url($url);
    dump($url_array);
    //用fsockopen()尝试连接 
    $fp = fsockopen($url_array['host'], 80, $errno, $errstr, 30);
    if (!$fp) {
        echo "$errstr ($errno)<br />\n";
    } else {
        //建立成功后,向服务器写入数据 
        $getPath = isset($url_array[&#39;path&#39;]) ? $url_array[&#39;path&#39;] : &#39;/&#39;;
        $out = "GET /".$getPath."/ HTTP/1.1\r\n";
        $out .= "Host:".$url_array[&#39;host&#39;]."\r\n";
        $out .= "Connection: Close\r\n\r\n";
       
        fwrite($fp, $out);
        /*忽略执行结果
        while (!feof($fp)) {
            echo fgets($fp, 128);
        }*/
        //关闭链接
        fclose($fp);
    }
}

Calling method

/**
*  异步方法
*  参数:(string)要执行的方法url,(array)传入参数
*/
function yibu(){
    $this->asynchronous(&#39;https://www.liqingbo.cn/index.php/admin/index/test&#39;,[&#39;1&#39;=>&#39;haha&#39;]);
    //直接返回结果
    echo &#39;操作成功&#39;;
}

Recommended tutorial: "PHP Video Tutorial"

The above is the detailed content of Asynchronous execution of PHP task fsockopen. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:liqingbo.cn. If there is any infringement, please contact admin@php.cn delete