【问题标题】:PHP file_get_contents() returns "failed to open stream: HTTP request failed!"PHP file_get_contents() 返回“打开流失败:HTTP 请求失败!”
【发布时间】:2010-10-16 09:31:55
【问题描述】:

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

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

我使用的代码是:

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

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

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

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

这很好用……难道我需要调用的网址中有第二个http://

【问题讨论】:

    标签: php api query-string file-get-contents


    【解决方案1】:

    尝试使用 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);
    
    ?>
    

    【讨论】:

    • 当真正的问题在于&符号时,这太复杂了。
    • @Christian,你能详细说明一下吗?
    • 不是每个人都(但应该)安装了 cURL。 cURL 确实要快很多倍,但 file_get_contents 也没有那么慢,并且不需要您在使用它时记住所有选项。
    • 这个CURLOPT_USERAGENT对我来说非常重要,谢谢!
    • 我相信我的问题是它超时了,这解决了它。谢谢!
    【解决方案2】:

    【讨论】:

    • 我遇到了与 OP 相同的错误,这是我的问题 - 参数中有空格。 GET 参数上的urlencode() 解决了这个问题。
    • 如果您不想使用 CURL 解决方案,这个可以!在参数上使用 URLecnode。
    • 这是这个问题的实际解决方案。
    【解决方案3】:
    <?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 );
        }
    }
    
    
    ?>
    

    【讨论】:

    • 感谢您的代码,看起来您来自:php.net/manual/en/ref.curl.php 主要问题是函数调用 get_url 实际上应该是 get_fcontent,因为您更改了函数本身的名称。这实际上是一个递归函数调用,通过更改一些参数重新尝试获取 URL 内容。
    • 你明白了!试图 https 并被拒绝。你搞定了。赞成 ;)
    【解决方案4】:

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

    您将需要更改您的 php.ini 以打开此选项或使用替代方法,即 cURL - 迄今为止最流行的,老实说,完成您想要做的事情的标准方法.

    【讨论】:

    • 没关系,只是注意到他说file_get_contents() 在不同的 URL 上工作。尽管如此,对于遇到此问题的其他人来说,这仍然是一个很好的提示。
    • 是的,我查看了其他选项,发现 cURL 是标准方法,但我尝试了这个,因为它更容易并与其他 url 一起使用,我想我必须重新启动 apache 才能安装 cURL?并且无法弄清楚如何做到这一点(另一个问题)...感谢您的快速回复
    【解决方案5】:

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

    试试这个,

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

    这对我有用

    【讨论】:

    • 这对我也有用!看起来它需要一个用户代理
    • 如果 url 看起来编码正确,这很可能是问题所在。某些网站会限制“用户代理”,也许还会限制“接受”。
    • 超级答案。投票支持将这个提升到顶部。全部在 php 中,也适用于 https 请求。只有两行额外的代码。如果共享服务器确实提供 curl 怎么办?这很有帮助。
    【解决方案6】:

    我注意到您的网址中有空格。我认为这通常是一件坏事。尝试使用

    对 URL 进行编码
    $my_url = urlencode("my url");
    

    然后调用

    file_get_contents($my_url);
    

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

    【讨论】:

      【解决方案7】:

      我遇到了类似的问题,我解析了 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'] : '';
      

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

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

      【讨论】:

        【解决方案8】:

        我遇到了类似的问题。

        由于超时!

        超时可以这样表示:

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

        【讨论】:

          【解决方案9】:

          我不确定参数(mpaction、格式)是否是为 amazonaws 页面或 ##.## 指定的。

          尝试urlencode()该网址。

          【讨论】:

          • 谢谢 - 这些是 mediaplug 实例的参数。如果我对 url 进行 urlencode 它仍然不起作用 - 我在错误中得到一个非常乱码的 url... ??
          • 你应该只编码参数字符串:“convert format”应该是“convert%20format”(或者“convert+format”)。
          【解决方案10】:
          $query=file_get_contents('http://###.##.##.##/mp/get?' . http_build_query(array('mpsrc' => 'http://mybucket.s3.amazonaws.com/11111.mpg&mpaction=convert format=flv')));
          

          【讨论】:

            【解决方案11】:

            这对我有用...我没有使用 curl。

            我能够通过浏览器访问特定的 API url,但是在 file_get_contents 中使用时,它给出了错误“无法打开流”。

            然后,我通过使用 urlencoding 对所有双引号进行编码来修改我想要调用的 API URL,并保持其他所有内容不变。

            示例格式如下:

            $url = 'https://stackoverflow.com/questions'.urlencode('"'.$variable1.'"');

            然后使用

            file_get_contents($url);

            【讨论】:

              【解决方案12】:

              有同样的问题,但这是一个防火墙问题...一旦我将 API 服务器列入白名单,它就可以正常工作,同时使用 get_file_contents($url) 和上面的 curl 方法...

              在发现防火墙规则问题之前浪费了数小时。

              【讨论】:

                【解决方案13】:

                对我来说,问题是 Content-Length 标头中的值不正确。值太大了,所以 nginx 一直在等待其余未到的内容。

                【讨论】:

                  【解决方案14】:

                  使用这个

                  file_get_contents($my_url,null,null);
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2016-06-02
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多