【问题标题】:file_get_contents not working as expected but curl works fine.file_get_contents 没有按预期工作,但 curl 工作正常。
【发布时间】:2014-02-04 14:12:52
【问题描述】:

我已经在我的服务器上测试了 file_get_contents,它几乎适用于所有网站,对于下面这个特定链接失败,但适用于 http://phpfiddle.org/

<?php

$homepage = file_get_contents('http://www.kinopoisk.ru/picture/10006/');
echo $homepage;

?>

我已经测试了这个链接http://www.kinopoisk.ru,它也适用于我的服务器,我检查了日志,没有那个链接的日志。由于主页正在打开,因此非常清楚 file_get_contents 在两个站点(我的站点和该站点)上都没有被禁用,所以如果有人能找出为什么它在我的页面中不起作用的问题,那就太好了。 我也尝试了 curl 和相同的空白输出。没有错误什么都没有。

<?php

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'http://www.kinopoisk.ru/picture/10006/');
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
$query = curl_exec($curl_handle);
curl_close($curl_handle);

?>

【问题讨论】:

  • ini_set('user_agent','whatever?'); 是否适用于第一个?

标签: php curl file-get-contents


【解决方案1】:

我看了你的两个代码 sn-ps。

在您的代码使用 curl 的 sn-p 中,HTTP 请求标头如下所示。

GET /picture/10006/ HTTP/1.1
User-Agent: Your application name
Host: www.kinopoisk.ru
Accept: */*

在您的代码使用 file_get_contents 的 sn-p 中,HTTP 请求标头如下所示。

GET /picture/10006/ HTTP/1.0
Host: www.kinopoisk.ru

这说明如果未设置 User-Agent 和 Accept-Header,www.kinopoisk.ru 上的网络服务器没有响应。我将您的第一个代码示例更改为以下内容,它现在可以工作了。

$opts = array(
    'http'=>array(
    'method'=>"GET",
    'header'=>"Accept: */*i\r\n" .
              "User-Agent: Your application name\r\n"
));
$context = stream_context_create($opts);
$homepage = file_get_contents('http://www.kinopoisk.ru/picture/10006/',0, $context);
print_r($homepage);

通过查看响应标头,我可以看到 www.kinopoisk.ru 上的服务器正在使用 Nginx,并且很可能配置为在未设置 Accept 和 User-Agent 标头时不返回响应。

【讨论】:

  • 没问题很高兴我能帮上忙
【解决方案2】:

使用 curl 解决了,但我仍然不知道为什么 file_get_contents 可以在一台服务器上工作,而不能在其他服务器上工作

<?php

$curl_handle=curl_init();
 curl_setopt($curl_handle, CURLOPT_URL,'http://www.kinopoisk.ru/picture/10006/');
   curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
 curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
  $query = curl_exec($curl_handle);
  curl_close($curl_handle);


 echo $query;
  ?>

【讨论】:

    猜你喜欢
    • 2019-12-20
    • 2018-08-21
    • 2017-08-02
    • 2021-05-20
    • 2021-10-19
    • 2020-03-18
    • 2012-06-14
    • 2014-11-15
    • 1970-01-01
    相关资源
    最近更新 更多