本文介绍了如何在 PHP 中发出异步 HTTP 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 中有没有办法进行异步 HTTP 调用?我不在乎响应,我只想做一些类似 file_get_contents() 的事情,但在执行我的其余代码之前不等待请求完成.这对于在我的应用程序中触发某种事件"或触发长进程非常有用.

Is there a way in PHP to make asynchronous HTTP calls? I don't care about the response, I just want to do something like file_get_contents(), but not wait for the request to finish before executing the rest of my code. This would be super useful for setting off "events" of a sort in my application, or triggering long processes.

有什么想法吗?

推荐答案

我之前接受的答案无效.它仍在等待回应.这确实有效,取自 我如何制作PHP 中的异步 GET 请求?

The answer I'd previously accepted didn't work. It still waited for responses. This does work though, taken from How do I make an asynchronous GET request in PHP?

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
";
    $out.= "Host: ".$parts['host']."
";
    $out.= "Content-Type: application/x-www-form-urlencoded
";
    $out.= "Content-Length: ".strlen($post_string)."
";
    $out.= "Connection: Close

";
    if (isset($post_string)) $out.= $post_string;

    fwrite($fp, $out);
    fclose($fp);
}

这篇关于如何在 PHP 中发出异步 HTTP 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 01:45