Asynchronous execution of PHP task fsockopen

coldplay.xixi
Release: 2023-04-08 19:16:01
forward
2131 people have browsed it

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)
\n"; } else { //建立成功后,向服务器写入数据 $getPath = isset($url_array['path']) ? $url_array['path'] : '/'; $out = "GET /".$getPath."/ HTTP/1.1\r\n"; $out .= "Host:".$url_array['host']."\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); /*忽略执行结果 while (!feof($fp)) { echo fgets($fp, 128); }*/ //关闭链接 fclose($fp); } }
Copy after login

Calling method

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

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!

Related labels:
source:liqingbo.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!