PHP file_get_contents() 返回“无法打开流:HTTP 请求失败!”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/697472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:33:23  来源:igfitidea点击:

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

phpapiquery-stringfile-get-contents

提问by undefined

I am having problems calling a url from PHP code. I need to call a service using a query string from my PHP code. If I type the url into a browser, it works ok, but if I use file-get-contents() to make the call, I get:

我在从 PHP 代码调用 url 时遇到问题。我需要使用 PHP 代码中的查询字符串调用服务。如果我在浏览器中输入 url,它工作正常,但如果我使用 file-get-contents() 进行调用,我得到:

Warning: file-get-contents(http://.... ) failed to open stream: HTTP request failed! HTTP/1.1 202 Accepted in ...

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

The code I am using is:

我正在使用的代码是:

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

Like I said - call from the browser and it works fine. Any suggestions?

就像我说的 - 从浏览器调用,它工作正常。有什么建议?

I have also tried with another url such as:

我也尝试过另一个网址,例如:

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

This works fine... could it be that the url I need to call has a second http://in it?

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

回答by James Hall

Try using 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);

?>

回答by pangeli

<?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 );
    }
}


?>

回答by Michael Wales

file_get_contents()utilizes the fopen()wrappers, therefore it is restricted from accessing URLs through the allow_url_fopenoption within php.ini.

file_get_contents()使用fopen()包装器,因此它被限制通过allow_url_fopenphp.ini 中的选项访问 URL 。

You will either need to alter your php.ini to turn this option on or use an alternative method, namely cURL- by far the most popular and, to be honest, standard way to accomplish what you are trying to do.

您要么需要更改 php.ini 以打开此选项,要么使用替代方法,即cURL- 迄今为止最流行的,老实说,是完成您要执行的操作的标准方法。

回答by d_bhatnagar

You basically are required to send some information with the request.

您基本上需要随请求发送一些信息。

Try this,

尝试这个,

$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);

This worked out for me

这对我有用

回答by slim

I notice that your URL has spaces in it. I think that usually is a bad thing. Try encoding the URL with

我注意到您的网址中有空格。我认为这通常是一件坏事。尝试对 URL 进行编码

$my_url = urlencode("my url");

and then calling

然后打电话

file_get_contents($my_url);

and see if you have better luck.

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

回答by Emre Karata?o?lu

I got a similar problem , I parsed the youtube url. The code is;

我遇到了类似的问题,我解析了 youtube 网址。代码是;

$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'] : '';

Then I realise that $this->video_urlinclude the whitespace. I solved that using trim($this->video_url).

然后我意识到$this->video_url包括空格。我使用trim($this->video_url).

Maybe it will help you . Good Luck

也许它会帮助你。祝你好运

回答by alexn

I'm not sure about the parameters(mpaction, format), if they are specified for the amazonaws page or ##.##.

我不确定参数(mpaction、格式),如果它们是为 amazonaws 页面或 ##.## 指定的。

Try to urlencode()the url.

尝试urlencode()url。

回答by Sergey

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

回答by Jerry

I got a similar problem.

我遇到了类似的问题。

Due to timeout !

由于超时!

Timeout can be indicated like this :

超时可以这样表示:

$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 =
$retour = @file_get_contents("http://xxxxx.xxx/xxxx", false, $context);