【问题标题】:php get request returns emptyphp 获取请求返回空
【发布时间】:2011-11-14 20:31:37
【问题描述】:

file_get_contents 在 url 上返回一个空字符串:http://thepiratebay.org/search/a

当它显然不为空时。 也试过 curl,这是我的代码

$ch = curl_init();
$cookieFile = 'cookies.txt';
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');

$url = 'http://thepiratebay.org/search/a';
curl_setopt($ch, CURLOPT_URL,$url);

$html = curl_exec ($ch);
var_dump($html);
$html = file_get_contents($url);
var_dump($html);

curl_close ($ch); unset($ch);

输出是:

string(143) "HTTP/1.1 200 OK
X-Powered-By: PHP/5.3.8
Content-type: text/html
Content-Length: 0
Date: Mon, 14 Nov 2011 20:27:01 GMT
Server: lighttpd

"
string(0) ""

如果我通过删除 2 个字符将 url 更改为“http://thepiratebay.org/search”,一切正常,我得到了很好的回应。

有什么想法吗?

【问题讨论】:

    标签: php curl


    【解决方案1】:

    问题是您尝试使用CURLOPT_TIMEOUT 设置用户代理字符串。尝试使用CURLOPT_USERAGENT,这应该可以解决您的问题。如果您更愿意使用file_get_contents,您可以使用stream_context_createini_set 来执行相同的操作。

    http://www.seopher.com/articles/how_to_change_your_php_user_agent_to_avoid_being_blocked_when_using_curl 提供了所有三种技术的示例。

    【讨论】:

    • 大声笑,愚蠢的错误,ty,这是 CURLOPT_USERAGENT,我最终用 python 写了这个:)
    【解决方案2】:

    file_get_contents 可能无法在您的安装中打开 URL。见fopen_wrappers。或者由于file_get_contents 呼叫中的用户代理,thepiratebay.org 可能会阻止您。尝试传递context。或者它没有返回任何内容,因为您没有像使用curl 那样在file_get_contents 调用中发送任何cookie。归根结底,即使 URL 相同,请求也不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多