首页 > 解决方案 > 如果图像无效,检查图像是否存在需要很长时间

问题描述

我有一个功能可以检查图像是否有效,以及是否在屏幕上打印 img。

<?php
function isImage($url){

$url_headers=get_headers($url, 1);

if($url_headers[0] == 'HTTP/1.1 404 Not Found') {
   $url_exists = false;
} 
else {
    $url_exists = true;
}

if($url_exists){
    if(isset($url_headers['Content-Type'])){
        $type=strtolower($url_headers['Content-Type']);

        $valid_image_type=array();
        $valid_image_type['image/png']='';
        $valid_image_type['image/jpg']='';
        $valid_image_type['image/jpeg']='';
        $valid_image_type['image/jpe']='';
        $valid_image_type['image/gif']='';

        if(isset($valid_image_type[$type])){
            return true;
        }
        else{
            return false;
        }
    }
}
}

if(isImage("http://curiosidadeslegais.org/wp-content/uploads/2016/08/zuera-pa-w5app.jpg")){
echo '<img src="http://curiosidadeslegais.org/wp-content/uploads/2016/08/zuera-pa-w5app.jpg" alt="">';
}

问题是我不知道为什么页面在上面的 url 中花了这么长时间。图像不再存在。和 html 打印:

<html>
<head>
<meta name="robots" content="noarchive" />
<meta name="googlebot" content="nosnippet" />
</head>
<body>
<div align=center>
<h3>Error. Page cannot be displayed. Please contact your service provider for more details.  (9)</h3>
</div>
</body>
</html>

我不知道为什么我的功能需要很长时间才能验证它不是图像并忽略它。任何想法为什么?

检查图像是否存在或不打印应该很快。但在这种情况下,它需要很长时间。

标签: phpcurl

解决方案


file_get_contents 可以返回标头并设置最大超时。

$options = stream_context_create(array('http'=>
array(
    "timeout" => 1, // one second
    "method" => "GET",
    "header" => "Accept-language: en\r\n" .
        "Cookie: foo=bar\r\n"
  )
));

$url_headers = file_get_contents($url, false, $options);

这是未经测试的,因为我正在手机上打字。

我在您的代码中注意到的另一件事是$url_exists = true;为什么?为什么不将下面的代码向上移动,并将上面的行替换为if($url_exists == true).
这不是代码缓慢的原因,但完全没有必要。


推荐阅读