PHP 中的异步 HTTP 请求:如何避免等待响应
在 PHP 中,处理 HTTP 请求通常涉及使用阻塞函数,如 file_get_contents( ),这会暂停脚本执行,直到收到响应。这会限制效率,尤其是在发出多个或非时间敏感请求时。
解决方案:非阻塞 HTTP 请求
为了克服此限制,PHP 提供了方法用于发出非阻塞 HTTP 请求。一种方法是使用stream_context_create():
$options = [ 'http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/json', 'content' => json_encode($data) ], 'ssl' => [ 'verify_peer' => false ] ]; $context = stream_context_create($options); file_get_contents("http://example.com/api", false, $context);
这会发起HTTP请求而不等待响应。但是,需要注意的是,verify_peer 选项设置为 false 以避免证书验证问题。
使用套接字自定义实现
另一个选项是直接使用创建套接字PHP 的 fsockopen() 函数:
function post_without_wait($url, $params) { // Prepare POST data and URL parameters $post_string = http_build_query($params); $url_parts = parse_url($url); $host = $url_parts['host']; $port = isset($url_parts['port']) ? $url_parts['port'] : 80; $socket = fsockopen($host, $port); // Construct HTTP POST request header $request = "POST {$url_parts['path']} HTTP/1.1\r\n"; $request .= "Host: {$host}\r\n"; $request .= "Content-Type: application/x-www-form-urlencoded\r\n"; $request .= "Content-Length: " . strlen($post_string) . "\r\n"; $request .= "Connection: Close\r\n\r\n"; $request .= $post_string; // Send HTTP request and close socket fwrite($socket, $request); fclose($socket); }
该函数发送 HTTP POST 请求,无需等待一个回应。它需要一个 URL 和一个参数数组作为参数。
以上是PHP 如何在不阻塞的情况下进行异步 HTTP 请求?的详细内容。更多信息请关注PHP中文网其他相关文章!