PHP的file_get_contents()函数返回“failed to open stream: HTTP request failed!”

112

我在使用PHP代码调用URL时遇到了问题。我需要在我的PHP代码中使用查询字符串来调用一个服务。如果我将URL键入浏览器,它可以正常工作,但是如果我使用file-get-contents()函数进行调用,我会得到以下错误信息:

警告:file-get-contents(http://.... )无法打开流:HTTP请求失败!HTTP/1.1 202 Accepted in ...

我正在使用的代码是:

$query=file_get_contents('http://###.##.##.##/mp/get?mpsrc=http://mybucket.s3.amazonaws.com/11111.mpg&mpaction=convert format=flv');
echo($query);

就像我说的一样- 通过浏览器调用是可以正常工作的。有什么建议吗?

我还尝试使用另一个URL:

$query=file_get_contents('http://www.youtube.com/watch?v=XiFrfeJ8dKM');

这个可以正常工作... 是否可能是我需要调用的网址中有第二个http://?

16个回答

127

尝试使用cURL。

<?php

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'http://###.##.##.##/mp/get?mpsrc=http://mybucket.s3.amazonaws.com/11111.mpg&mpaction=convert format=flv');
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);

?>

12
问题实际上出在“&”符号,但这句话过于复杂。 - Christian
3
@Christian,你能详细说明一下吗? - vonUbisch
6
并非每个人都安装了cURL(但他们应该安装)。cURL 确实快得多,但 file_get_contents 的速度也不是“太慢”,而且使用它不需要记住所有选项。 - Christian
1
这个CURLOPT_USERAGENT在我的情况下非常重要,谢谢! - emotality
我相信我的问题是由于超时引起的,这个修复了它。谢谢! - backend_dev_123
有没有一种便宜而且简单的方法使用curl下载文件? - Yash Kumar Verma

33

我遇到了和 OP 一样的错误,问题在于参数中有空格。对 GET 参数使用 urlencode() 解决了这个问题。 - Walt W
如果您不想使用CURL解决方案,这个方法也可以!在参数上使用URLecnode。 - Aaron Gong
1
这是解决此问题的实际方案。 - Henrik Petterson

24
<?php

$lurl=get_fcontent("http://ip2.cc/?api=cname&ip=84.228.229.81");
echo"cid:".$lurl[0]."<BR>";


function get_fcontent( $url,  $javascript_loop = 0, $timeout = 5 ) {
    $url = str_replace( "&amp;", "&", urldecode(trim($url)) );

    $cookie = tempnam ("/tmp", "CURLCOOKIE");
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $ch, CURLOPT_ENCODING, "" );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );    # required for https urls
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
    $content = curl_exec( $ch );
    $response = curl_getinfo( $ch );
    curl_close ( $ch );

    if ($response['http_code'] == 301 || $response['http_code'] == 302) {
        ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");

        if ( $headers = get_headers($response['url']) ) {
            foreach( $headers as $value ) {
                if ( substr( strtolower($value), 0, 9 ) == "location:" )
                    return get_url( trim( substr( $value, 9, strlen($value) ) ) );
            }
        }
    }

    if (    ( preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value) ) && $javascript_loop < 5) {
        return get_url( $value[1], $javascript_loop+1 );
    } else {
        return array( $content, $response );
    }
}


?>

8
感谢您提供的代码,看起来您是从http://php.net/manual/en/ref.curl.php获取的。主要问题在于函数调用`get_url`实际上应该是`get_fcontent`,因为您已经更改了函数本身的名称。这实际上是一个递归函数调用,通过更改某些参数重新尝试获取URL内容。 - SSH This
你做到了!我一直在尝试使用HTTPS,但总是失败。你成功了。点赞 ;) - tony gil

23

file_get_contents()使用fopen()包装器,因此无法通过php.ini中的allow_url_fopen选项访问URL。

您需要修改php.ini以打开此选项,或者使用另一种方法,即cURL-这是迄今为止最流行和标准的方法,老实说,这是您尝试做的事情的标准方法。


没事了,我刚注意到他说file_get_contents()在另一个URL上起作用了。尽管如此,对于其他遇到这个问题的人来说,这仍然是一个很好的提示。 - Michael Wales
是的,我已经看过其他选项了,发现cURL是标准的方法,但我尝试了这个因为它更容易并且可以与其他url一起使用。我想我必须重新启动apache来安装cURL?但我不知道如何做到这一点(另一个问题)...感谢您的快速回复。 - undefined

19
您基本上需要在请求中发送一些信息。
请试试这个,
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n")); 
//Basically adding headers to the request
$context = stream_context_create($opts);
$html = file_get_contents($url,false,$context);
$html = htmlspecialchars($html);

这对我起作用了


2
这对我也起作用了!看起来需要一个用户代理。 - bryan
如果URL看起来已经被正确编码,那么这很可能是问题所在。有些网站会限制“User-Agent”,也可能限制“Accept”。 - James John McGuire 'Jahmic'
2
超级棒的答案。投票支持将其推到顶部。全部使用PHP编写,也适用于HTTPS请求。只需两行额外的代码。如果共享服务器提供curl呢?这非常有帮助。 - ndasusers

14

我注意到你的URL中有空格。通常情况下,这是不好的。尝试使用编码来对URL进行编码。

$my_url = urlencode("my url");

然后调用

file_get_contents($my_url);

看看你是否有更好的运气。


6

我遇到了类似的问题。

这是由于超时引起的!

超时可以用以下方式表示:

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => "POST",
        'content' => http_build_query($data2),
        'timeout' => 30,
    ),
);
$context = stream_context_create($options);
$retour = @file_get_contents("http://xxxxx.xxx/xxxx", false, $context);

$data2 中的内容是什么? - Nishad Up
您好!$data2是一个数组,用于向远程脚本传递变量。 - Jerry

4

我遇到了类似的问题,我解析了YouTube的URL。代码如下:

$json_is = "http://gdata.youtube.com/feeds/api/videos?q=".$this->video_url."&max-results=1&alt=json";
$video_info = json_decode ( file_get_contents ( $json_is ), true );     
$video_title = is_array ( $video_info ) ? $video_info ['feed'] ['entry'] [0] ['title'] ['$t'] : '';

然后我意识到$this->video_url包含空格。我使用trim($this->video_url)解决了这个问题。

也许这会对你有所帮助。祝好运!


2

我不确定参数(mpaction, format)是为amazonaws页面还是##.##页面指定的。

尝试使用urlencode()对URL进行编码。


谢谢 - 这些是mediaplug实例的参数。如果我对url进行urlencode,它仍然无法工作 - 我会在错误中得到一个非常混乱的url... - undefined
你应该只对参数字符串进行编码: "convert format" 应该是 "convert%20format"(或者是 "convert+format")。 - bobince

2
这个函数解决了我的问题。

function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}


1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community
谢谢,对我来说完全没问题。:) - user2812532

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