【问题标题】:file_get_contents returns HTTP/1.1 301 Moved Permanentlyfile_get_contents 返回 HTTP/1.1 301 永久移动
【发布时间】:2016-07-04 21:25:07
【问题描述】:

我想获取 url 的内容,当我使用 file_get_contents 方法时,它返回 HTTP/1.1 301 Moved Permanently。但是在浏览器中链接可以正常工作。

我也试过 curl 函数,但它返回同样的问题。代码是

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $page_url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
if(preg_match('#Location: (.*)#', $a, $r))
$xx = trim($r[1]);

提前致谢!

【问题讨论】:

    标签: php http


    【解决方案1】:

    更改以下内容,因为 curl 应该能够跟随重定向 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

    【讨论】:

      【解决方案2】:

      试试这个

          $ch= curl_init();
          curl_setopt ($ch, CURLOPT_URL, $page_url );
          curl_setopt($ch, CURLOPT_HEADER, 0);
          curl_setopt($ch,CURLOPT_VERBOSE,1);
          curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)');
          curl_setopt ($ch, CURLOPT_REFERER,'http://www.google.com');  //just a fake referer
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($ch,CURLOPT_POST,0);
          curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
          $htmlContent= curl_exec($ch);
          curl_close($ch);
      

      【讨论】:

      • 感谢您的回复,我找到了答案,但我也尝试了您的答案。它运行良好。
      • @KrishKowsi 根据接受的答案,file_get_contents() 不适用于每个网站。一些网站有allow_url_fopen 禁用。因此您将无法从该网站获取内容。 cURL 库将完美运行。如果您需要更多帮助,请告诉我。
      【解决方案3】:

      谢谢大家。我找到了我的问题的答案。

      $opts = array('http'=>array('header' => "User-Agent:Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\r\n"));
      $context = stream_context_create($opts);
      $buffer = file_get_contents($row['url'],false,$context);
      

      【讨论】:

      • 为什么会这样?提供 User-Agent 标头会阻止网站重定向吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 2019-11-04
      • 2012-07-10
      • 2013-09-26
      相关资源
      最近更新 更多