【问题标题】:How do I ignore a moved-header with file_get_contents in PHP?如何在 PHP 中忽略带有 file_get_contents 的移动标题?
【发布时间】:2011-08-25 22:35:56
【问题描述】:

我编写了一个简单的内容用户,它使用 file_get_contents,但不幸的是,对于我的 IP,该站点现在给出了一个 302 错误,该错误会转发到图像。对于所有其他用户,正常站点是可见的。

如何重写 get_contents 使其仅下载网站内容而不实际遵循重定向?

$html = file_get_contents("http://www.site.net/");

【问题讨论】:

    标签: php


    【解决方案1】:

    你需要创建一个上下文:

    $context = stream_context_create(
        array (
            'http' => array (
                'follow_location' => false // don't follow redirects
            )
        )
    );
    $html = file_get_contents('http://www.site.net/', false, $context);
    

    参见手册:

    话虽如此,页面上很可能没有任何内容。提供 302 标头和 HTTP 正文并非不可能,但这绝对是非正统的。

    【讨论】:

    • 请记住,'follow_location' 仅从 PHP 5.3.4 开始可用(无论如何,每个人都应该运行比它更新的东西。)内部数组中的“max_redirects => 0”也是必要的(请参阅php.net/manual/en/context.http.php 上的示例 #2)
    【解决方案2】:

    那里没有内容。在发送任何内容之前,重定向发生在 HTTP 响应中。

    服务器决定你看到(或不看到)什么。

    【讨论】:

    • 重定向发生在 HTTP 响应标头中。但是,配置错误的服务器可能会发送输出,即使它正在发送新位置以及响应代码 302。
    • 这个答案不正确(为避免任何疑问)。正如@Oliver 所说,假设没有使用 302 发送任何内容是不安全的。
    【解决方案3】:

    我在通过直接链接访问 Google 云端硬盘内容时遇到了此类问题。

    NICE WAY:使用下面的代码再次运行:

    //Any google url. Thsi example is fake for Google Drive direct link.
    $url = "https://drive.google.com/uc?id=0BxQKKJYjuNElbFBNUlBndmVHHAj";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);  
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 3);     
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $html = curl_exec($ch);
    curl_close($ch);
    
    echo $html;
    

    我今天测试了它,2018 年 3 月 19 日

    错误的方式:调用 file_get_contents 后返回 302 暂时移动

    //Any google url. Thsi example is fake for Google Drive direct link.
    $url = "https://drive.google.com/uc?id=0BxQKKJYjuNElbFBNUlBndmVHHAj";
    $html = file_get_contents($url);
    echo $html; //print none because error 302.
    

    【讨论】:

    • 不是file_get_contents
    • 你知道你写了什么吗? file_get_contents 是错误的示例。
    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    相关资源
    最近更新 更多