douou5933 2009-06-07 21:53
浏览 152
已采纳

如何在PHP中创建异步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

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.

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

Thanks all

Update

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?

  • 写回答

22条回答 默认 最新

  • doufu1950 2009-06-07 21:56
    关注

    file_get_contents will do what you want

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

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

    Quoted from 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);
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(21条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大