如何检查是否可以显示远程图像?

问题描述 投票:0回答:1

来自远程服务器的图像有时不会显示在我的网站上。他们坏了。在检查控制台时获取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
)
php image http-headers
1个回答
0
投票

检查图像大小。这是最简单,最有效的解决方案:

list($width, $height, $type, $attr) = getimagesize("www.url.com/img.jpg");

如果特别是前两个;设置$width$height$type是一个有用的值,你很高兴。

我会在这种情况下显示它们。

© www.soinside.com 2019 - 2024. All rights reserved.