我希望向不同服务器上的另一个脚本发出一个简单的GET请求。我该怎么做呢?
在一种情况下,我只需要请求一个外部脚本,而不需要任何输出。
make_request('http://www.externalsite.com/script1.php?variable=45'); //example usage
在第二种情况下,我需要获取文本输出。
$output = make_request('http://www.externalsite.com/script2.php?variable=45');
echo $output; //string output
老实说,我不想和CURL打交道,因为这真的不是CURL的工作。我也不想使用http_get,因为我没有PECL扩展。
fsockopen能工作吗?如果是这样,如何在不读取文件内容的情况下执行此操作?没有别的办法了吗?
感谢所有人
更新
我应该补充说,在第一种情况下,我不想等待脚本返回任何东西。据我所知,file_get_contents()将等待页面完全加载,等等?
发布于 2009-06-07 21:56:12
file_get_contents
会做你想做的事
$output = file_get_contents('http://www.example.com/');
echo $output;
编辑:触发GET请求并立即返回的一种方法。
引用自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请求,然后立即关闭该套接字并返回。
发布于 2010-10-16 03:31:39
下面是如何让Marquis的回答同时处理POST和GET请求:
// $type must equal 'GET' or 'POST'
function curl_request_async($url, $params, $type='POST')
{
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);
// Data goes in the path for a GET request
if('GET' == $type) $parts['path'] .= '?'.$post_string;
$out = "$type ".$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";
// Data goes in the request body for a POST request
if ('POST' == $type && isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
发布于 2012-11-25 05:00:08
我建议您使用经过良好测试的PHP库:curl-easy
<?php
$request = new cURL\Request('http://www.externalsite.com/script2.php?variable=45');
$request->getOptions()
->set(CURLOPT_TIMEOUT, 5)
->set(CURLOPT_RETURNTRANSFER, true);
// add callback when the request will be completed
$request->addListener('complete', function (cURL\Event $event) {
$response = $event->response;
$content = $response->getContent();
echo $content;
});
while ($request->socketPerform()) {
// do anything else when the request is processed
}
https://stackoverflow.com/questions/962915
复制相似问题