如何在PHP中创建异步GET请求? [英] How do I make an asynchronous GET request in 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
说实话,我不想搞乱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?
感谢所有
我应该添加,在第一种情况下,我不想等待脚本返回任何东西。
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
file_get_contents
will do what you want
$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\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);
}
这样做是打开一个套接字,触发get请求,关闭套接字并返回。
What this does is open a socket, fire off a get request, and immediately close the socket and return.
这篇关于如何在PHP中创建异步GET请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!