PHP如果图像文件不存在,则显示另一个图像


PHP if image file doesn't exist, show another image

我想知道是否有人能够帮助我这个PHP脚本,我正在使用一个Jquery Nivo幻灯片。该脚本从文本文件中获取文件名,并通过分页根据您所在的页面显示文件名。

如果文件不存在,脚本是否有办法显示另一个图像?例如,如果images/work/目录中不存在image1.jpg,则会显示image unavailable.jpg。

脚本:

 <?php
 echo"
<div class='slider-wrapper theme-custom'>
<div id='slider' class='nivoSlider'>";
$photos=file("photos.txt");
foreach($photos as $image){
$item=explode("|",$image);
if($item[0]==$fields[0]){
$photo=trim($item[1]);
echo"<img src='images/work/$photo' alt='' />'n";
}
}
echo"
</div>
</div>
"?>

foreach ($photos as $image) {
    ... explode
    ... trim
    if (!is_readable($your_document_root . '/images/work/$photo)) {
       $photo = 'default.jpg'; // if the required photo isn't there, change to default image
    }
    echo blah blah blah
}

请注意,我已经使用了is_readable() -有些人可能会建议使用file_exists(),但这可能会返回一个假阳性:文件可能存在,但由于权限问题仍然无法读取。is_readable()将两者结合,只有当文件存在可被web服务器访问时才返回true。

如果您的服务器上有file_exists(),则可以使用它。它接受文件的路径作为参数,而不是URL。

http://php.net/manual/en/function.file-exists.php

你需要file_exists();

返回布尔值。在if语句中使用它。如果您有适当的权限访问这些图像