【发布时间】:2011-08-25 22:35:56
【问题描述】:
我编写了一个简单的内容用户,它使用 file_get_contents,但不幸的是,对于我的 IP,该站点现在给出了一个 302 错误,该错误会转发到图像。对于所有其他用户,正常站点是可见的。
如何重写 get_contents 使其仅下载网站内容而不实际遵循重定向?
$html = file_get_contents("http://www.site.net/");
【问题讨论】:
标签: php
我编写了一个简单的内容用户,它使用 file_get_contents,但不幸的是,对于我的 IP,该站点现在给出了一个 302 错误,该错误会转发到图像。对于所有其他用户,正常站点是可见的。
如何重写 get_contents 使其仅下载网站内容而不实际遵循重定向?
$html = file_get_contents("http://www.site.net/");
【问题讨论】:
标签: php
你需要创建一个上下文:
$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 正文并非不可能,但这绝对是非正统的。
【讨论】:
那里没有内容。在发送任何内容之前,重定向发生在 HTTP 响应中。
服务器决定你看到(或不看到)什么。
【讨论】:
我在通过直接链接访问 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。