检查图像是否存在,如果没有使用php显示默认图像

时间:2015-05-20 16:11:54

标签: php image loops

我已经尝试过file_exists和getimagesize,但页面加载速度非常慢,所以我想尝试这种方式,如下所示...... 首先,我使用循环获取所有图像的列表,如下所示

foreach(glob('./images/*.png') as $filename){
           $ImagesArray[] = $filename;
           }

然后我有另一个循环,它从另一个数组获取值后生成div。在这个循环中,如果没有选择默认图像,我会检查图像是否存在。

foreach ($populartags as $word => $count) {

$DefaultImage = './images/tag.png';

    if (in_array("./images/$word.png", $ImagesArray)){

            $DefaultImage = './images/'.$word.'.png'; }


....output image
}

但结果是:它只显示图像文件夹中存在的图像。然后对于其他人,它没有显示默认图像。 这段代码有什么问题??

1 个答案:

答案 0 :(得分:0)

为什么不简单地使用htaccess规则呢?

这样的东西会显示请求的图像,或者是默认的图像, 如果请求的图像不存在(仅在此图像中使用.gif):

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} .*\.gif$
RewriteRule .* default.gif