当使用浏览器打开URL并且URL有效时,file_get_contents返回404。

5
我得到了以下错误:
警告:file_get_contents(https://www.readability.com/api/content/v1/parser?url=http://www.redmondpie.com/ps1-and-ps2-games-will-be-playable-on-playstation-4-very-soon/?utm_source=dlvr.it&utm_medium=twitter&token=MYAPIKEY) [function.file-get-contents]:打开流失败!HTTP/1.1 404 NOT FOUND in /home/DIR/htdocs/readability.php on line 23
通过一些回显,我得到了函数解析的URL,并且它是正确和有效的,我从浏览器中进行请求也是可以的。
问题是我使用file_get_contents时得到了上述错误,我真的不明白为什么。
URL是有效的,函数没有被免费托管服务阻止(所以我不需要Curl)。
如果有人能发现我的代码中的错误,我将不胜感激!谢谢...
这是我的代码:
<?php

class jsonRes{
    public $url;
    public $author;
    public $url;
    public $image;
    public $excerpt;
}

function getReadable($url){
 $api_key='MYAPIKEY';
 if(isset($url) && !empty($url)){

    // I tried changing to http, no 'www' etc... -THE URL IS VALID/The browser opens it normally-

    $requesturl='https://www.readability.com/api/content/v1/parser?url=' . urlencode($url) . '&token=' . $api_key;
    $response = file_get_contents($requesturl);   // * here the code FAILS! *

    $g = json_decode($response);

    $article_link=$g->url;
    $article_author='';
    if($g->author != null){
       $article_author=$g->author;
    }

    $article_url=$g->url;
    $article_image=''; 
    if($g->lead_image_url != null){
        $article_image=$g->lead_image_url;
    }
    $article_excerpt=$g->excerpt;

    $toJSON=new jsonRes();
    $toJSON->url=$article_link;
    $toJSON->author=$article_author;
    $toJSON->url=$article_url;
    $toJSON->image=$article_image;
    $toJSON->excerpt->$article_excerpt;

    $retJSONf=json_encode($toJSON);
    return $retJSONf;
 }
}
?>

你可能不一定需要curl,但我强烈建议使用它。file_get_contents()对于远程URL来说是一个非常笨重的工具。 - user557846
1个回答

3
有时候,网站会阻止爬虫(来自远程服务器)访问他们的页面。
为了绕过这个问题,他们会伪造浏览器头部信息。比如,假装是Mozilla Firefox而不是一个隐秘的PHP网络爬虫。
这是一个使用cURL库实现这一功能的函数。
function get_data($url) {

$userAgent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13';

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
if (!$html) {
    echo "<br />cURL error number:" .curl_errno($ch);
    echo "<br />cURL error:" . curl_error($ch);
    exit;
}
else{
    return $html;
}

//End of cURL function

}

那么,就可以按照以下方式进行调用:
$response = get_data($requesturl);

Curl在获取远程内容和错误检查方面比file_get_contents提供了更多的选项。如果您想进一步自定义它,请查看这里的cURL选项列表 - cURL选项列表

1
我遇到了完全相同的问题,但是这个解决方案也给了我一个404错误。你做了哪些修改? - Patrick Bard
答案中指定的用户代理对我无效,但这个有效:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36 - Asrar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接