如何在PHP中发出异步HTTP请求
时间:2020-03-06 14:38:02 来源:igfitidea点击:
PHP中有没有办法进行异步HTTP调用?我不在乎响应,我只想做类似file_get_contents()
的事情,但不等待请求完成才执行其余代码。这对于在我的应用程序中触发某种"事件"或者触发较长的进程非常有用。
有任何想法吗?
解决方案
我们可以通过使用exec()调用可以执行HTTP请求的操作来欺骗,例如wget,但是我们必须将程序的所有输出定向到某个位置,例如文件或者/ dev / null,否则PHP进程将等待对于该输出。
如果我们想将进程与apache线程完全分开,请尝试类似的操作(我不确定,但是希望我们能理解):
exec('bash -c "wget -O (url goes here) > /dev/null 2>&1 &"');
这不是一件好事,我们可能想要像cron作业那样调用心跳脚本的事情,该脚本会轮询实际的数据库事件队列以执行真正的异步事件。
这需要php5,
我从docs.php.net中偷了出来,并编辑了结尾。
我用它来监视客户端站点上何时发生错误,它会向我发送数据而不会阻止输出
function do_post_request($url, $data, $optional_headers = null,$getresponse = false) { $params = array( 'http' => array( 'method' => 'POST', 'content' => $data ) ); if ($optional_headers !== null) { $params['http']['header'] = $optional_headers; } $ctx = stream_context_create($params); $fp = @fopen($url, 'rb', false, $ctx); if (!$fp) { return false; } if ($getresponse) { $response = stream_get_contents($fp); return $response; } return true; }
如果我们控制要异步调用的目标(例如,我们自己的" longtask.php"),则可以从该端关闭连接,这两个脚本将并行运行。它是这样的:
- quick.php通过cURL打开longtask.php(这里没有魔术)
- longtask.php关闭连接并继续(魔术!)
- 关闭连接后,cURL返回到quick.php
- 两项任务并行进行
我已经尝试过了,而且效果很好。但是quick.php不会对longtask.php的工作一无所知,除非我们在进程之间创建某种通信方式。
在执行其他任何操作之前,请在longtask.php中尝试此代码。它将关闭连接,但仍继续运行(并抑制任何输出):
while(ob_get_level()) ob_end_clean(); header('Connection: close'); ignore_user_abort(); ob_start(); echo('Connection Closed'); $size = ob_get_length(); header("Content-Length: $size"); ob_end_flush(); flush();
该代码是从PHP手册的用户贡献注释中复制而来,并有所改进。
/** * Asynchronously execute/include a PHP file. Does not record the output of the file anywhere. * * @param string $filename file to execute, relative to calling script * @param string $options (optional) arguments to pass to file via the command line */ function asyncInclude($filename, $options = '') { exec("/path/to/php -f {$filename} {$options} >> /dev/null &"); }
我以前接受的答案没有用。它仍然在等待回应。但这确实有效,取自我如何在PHP中发出异步GET请求?
function post_without_wait($url, $params) { foreach ($params as $key => &$val) { if (is_array($val)) $val = implode(',', $val); $post_params[] = $key.'='.urlencode($val); } $post_string = implode('&', $post_params); $parts=parse_url($url); $fp = fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80, $errno, $errstr, 30); $out = "POST ".$parts['path']." HTTP/1.1\r\n"; $out.= "Host: ".$parts['host']."\r\n"; $out.= "Content-Type: application/x-www-form-urlencoded\r\n"; $out.= "Content-Length: ".strlen($post_string)."\r\n"; $out.= "Connection: Close\r\n\r\n"; if (isset($post_string)) $out.= $post_string; fwrite($fp, $out); fclose($fp); }