The main content of this article is to use PHP to implement asynchronous requests and ignore return values. It has certain reference value. Friends in need can take a look. I hope it will be helpful to you.
Project needs, the scenario is as follows:
Under certain conditions, the interface needs to be called to send multiple requests to execute the script, but since the script execution time under each request is about half an hour, so Give up and return the execution result. It only requires that it can be sent within seconds.
The code is as follows:
/** * 发起异步请求,忽略返回值 * @param $url 请求url * @return bool */ function asyncPost($url) { $args = parse_url($url); //对url做下简单处理 $host = $args['host']; //获取上报域名 $path = $args['path'] . '?' . $args['query'];//获取上报地址 $fp = fsockopen($host, 80, $error_code, $error_msg, 1); if (!$fp) { Log::record('获取错误信息:'.$error_code . ' _ ' . $error_msg, Log::INFO, true); Log::save('',LOG_PATH . '_' . date('y_m_d') . '.txt'); return false;// } else { stream_set_blocking($fp, true);//开启了手册上说的非阻塞模式 stream_set_timeout($fp, 1);//设置超时 $header = "GET $path HTTP/1.1\r\n"; //注意 GET/POST请求都行 我们需要自己按照要求拼装Header http协议遵循1.1 $header .= "Host: $host\r\n"; $header .= "Connection: close\r\n\r\n";//长连接关闭 fputs($fp, $header); fclose($fp); } }
The example is as follows:
$url[0] = "http://XXXX/demo.php?a=1&b=2&c=3&d=4&e=5"; $url[1] = "http://XXXX/demo.php?a=1&b=2&c=3&d=4&e=5"; $url[2] = "http://XXXX/demo.php?a=1&b=2&c=3&d=4&e=5"; $url[3] = "http://XXXX/demo.php?a=1&b=2&c=3&d=4&e=5"; $url[4] = "http://XXXX/demo.php?a=1&b=2&c=3&d=4&e=5"; $url[5] = "http://XXXX/demo.php?a=1&b=2&c=3&d=4&e=5"; foreach($url as $k=>$val){ asyncPost($val); }
The result is as follows:
The above is me The results of multiple tests, the time range is as above.
Related tutorials: PHP video tutorial
The above is the detailed content of How to use PHP to implement asynchronous requests and ignore return values. For more information, please follow other related articles on the PHP Chinese website!