如何在 PHP 中发出异步 GET 请求? [英] How do I make an asynchronous GET request in PHP?

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

问题描述

我希望向不同服务器上的另一个脚本发出一个简单的 GET 请求.我该怎么做?

I wish to make a simple GET request to another script on a different server. How do I do this?

在一种情况下,我只需要请求一个外部脚本而不需要任何输出.

In one case, I just need to request an external script without the need for any output.

make_request('http://www.externalsite.com/script1.php?variable=45'); //example usage

在第二种情况下,我需要获取文本输出.

In the second case, I need to get the text output.

$output = make_request('http://www.externalsite.com/script2.php?variable=45');
echo $output; //string output

老实说,我不想弄乱 CURL,因为这不是 CURL 的工作.我也不想使用 http_get,因为我没有 PECL 扩展.

To be honest, I do not want to mess around with CURL as this isn't really the job of CURL. I also do not want to make use of http_get as I do not have the PECL extensions.

fsockopen 能用吗?如果是这样,如何在不读取文件内容的情况下执行此操作?没有别的办法了吗?

Would fsockopen work? If so, how do I do this without reading in the contents of the file? Is there no other way?

谢谢大家

我应该补充一点,在第一种情况下,我不想等待脚本返回任何内容.据我了解 file_get_contents() 会等待页面完全加载等?

I should of added, in the first case, I do not want to wait for the script to return anything. As I understand file_get_contents() will wait for the page to load fully etc?

推荐答案

file_get_contents 随心所欲

$output = file_get_contents('http://www.example.com/');
echo $output;

一种触发 GET 请求并立即返回的方法.

One way to fire off a GET request and return immediately.

引自 http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html

function curl_post_async($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);
}

它的作用是打开一个套接字,发出一个 get 请求,然后立即关闭套接字并返回.

What this does is open a socket, fire off a get request, and immediately close the socket and return.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆