使用cURL获取错误代码28

时间:2011-07-13 11:59:11

标签: php json curl

这已经解决了 - 在本帖结束时看到了答案

我正在尝试使用PHP / cURL

从远程服务器检索数据

如果我将以下网址放入浏览器,数据会正确显示。

http://realm103.c7.castle.wonderhill.com/api/map.json?user%5Fid=5245274&x=375&y=375&timestamp=1310554325&%5Fsession%5Fid=5b2070a46a083a33e053d60dbc2d062e&dragon%5Fheart=098d2deb0a37f18c97428d636c456572f9bade24&version=3

然而,当我尝试使用PHP / cURL访问时,它只是超时(错误代码28)。

$json = curl($jsonurl, $realm['intRealmID'], $realm['strRealmServer']);

function curl($url, $realm, $realmServer){
$header = array();
$header[] = 'Host: realm'.strval($realm).'.'.$realmServer.'.castle.wonderhill.com';
$header[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
$header[] = 'Accept-Language: en-us,en;q=0.5';
$header[] = 'Accept-Encoding: gzip,deflate';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Connection: keep-alive';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
return curl_exec($ch);
curl_close($ch);

}

任何人都有任何想法,为什么它可以从浏览器工作但不通过cURL?感谢

其他信息 虽然cURL不适用于上面的URL。对于下面的URL,它工作得很好。唯一的区别是服务器请求数据。数据本身和POST是完全相同的。

http://realm4.c5.castle.wonderhill.com/api/map.json?user%5Fid=1053774&x=375&y=375&timestamp=1310616808&%5Fsession%5Fid=5b2070a46a083a33e053d60dbc2d062e&dragon%5Fheart=f35f476facab91f0e901eaf2209a0c8a9b9bedcc&version=3

ANSWER

最后回到此处,发现推荐人是问题所在。服务器期望在请求标头中看不到引用者。当它发出请求时被阻止了。这种行为在当时所有服务器上可能并不一致,但现在却是如此。从请求标题中删除引用者并将其他所有内容保持不变现在可以正常工作。

2 个答案:

答案 0 :(得分:1)

您的cURL函数与直接请求信息之间的最大区别是CURLOPT_HEADER属性,我首先尝试从代码中删除它。

答案 1 :(得分:1)

试试这个

function get_data($url)
 {
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
 }

 $returned_content = get_data('your url');

或者,您可以远程使用file_get_contents功能,但许多主机不允许此

$userAgent = ‘Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0’;
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);

我使用的其他一些选项:

curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

试试这个:

 $ctx = stream_context_create( array(
                 'socket' => array(
                             'bindto' => '192.168.0.107:0',
    )
   ));

   $c= file_get_contents('http://php.net', 0, $ctx);