【发布时间】:2018-02-28 13:23:21
【问题描述】:
来自远程服务器的图像有时不会显示在我的网站上。他们坏了。并在控制台签入时获得403 (Forbidden)。
所以我想找到一种方法来预先检查它们是否被禁止,然后不显示它们,而不是显示损坏的图像。
所以,我的想法是使用 get_headers() 检查 http 状态。但即使是损坏的图像,它也会显示200 OK。
然后我在谷歌搜索后找到了这个解决方案,在get_headers()之前使用:
$default_opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Referer: http://www.fakesite.com/hotlink-check/",
)
);
stream_context_set_default($default_opts);
但这也不起作用。我也尝试过file_get_contents(),但这给出了未损坏和损坏图像的结果。
那么,如何检查远程文件是否有403错误?
编辑:
好的,这是我最近尝试过的测试:
$image = 'http://www.arabnews.com/sites/default/files/2018/02/28/1114386-582723106.jpg';
测试 1:
<?php
$default_opts = array(
'http' => array(
'method' => "GET",
'header' => "Referer: http://www.fakesite.com/hotlink-check/",
'user_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6',
)
);
stream_context_set_default($default_opts);
$output = @get_headers($image, 1);
echo '<pre>'.print_r($output, true).'</pre>';
?>
输出:
Array
(
[0] => HTTP/1.1 200 OK
[Date] => Wed, 28 Feb 2018 14:50:39 GMT
[Content-Type] => image/jpeg
[Content-Length] => 43896
[Connection] => close
[Set-Cookie] => __cfduid=d2a28d117e8a32d5755219bcd6e1892561519829439; expires=Thu, 28-Feb-19 14:50:39 GMT; path=/; domain=.arabnews.com; HttpOnly
[X-Content-Type-Options] => nosniff
[Last-Modified] => Tue, 27 Feb 2018 22:55:30 GMT
[Cache-Control] => public, max-age=1209600
[Expires] => Wed, 14 Mar 2018 14:50:39 GMT
[X-Request-ID] => v-e065c0be-1c11-11e8-9caa-22000a6508a2
[X-AH-Environment] => prod
[X-Varnish] => 175579289 178981578
[Via] => 1.1 varnish-v4
[X-Cache] => HIT
[X-Cache-Hits] => 8
[CF-Cache-Status] => HIT
[Accept-Ranges] => bytes
[Server] => cloudflare
[CF-RAY] => 3f44328fd0247179-ORD
)
测试 2:
<?php
function get_response_code($url) {
@file_get_contents($url);
list($version, $status, $text) = explode(' ', $http_response_header[0], 3);
return $status;
}
$output = get_response_code($image);
echo '<pre>'.print_r($output, true).'</pre>';
?>
输出:
200
测试 3:
<?php
$output = getimagesize($image);
echo '<pre>'.print_r($output, true).'</pre>';
?>
输出:
Array
(
[0] => 650
[1] => 395
[2] => 2
[3] => width="650" height="395"
[bits] => 8
[channels] => 3
[mime] => image/jpeg
)
【问题讨论】:
-
远程服务器拒绝提供文件的原因可能因您的服务器和浏览器不同。当图像无法加载并替换它或隐藏它时,您可能希望附加一个 Javascript 事件处理程序。
-
尝试为http流上下文设置
user_agent -
@Dan Miller 好的,比如,什么用户代理?值应该是多少?
-
类似
Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6的东西只是为了模拟用户浏览器,我不确定它是否会工作 -
丹米勒:没用。请参阅上面我编辑的帖子。
标签: php image http-headers