【问题标题】:PHP if image file doesn't exist, show another imagePHP 如果图像文件不存在,则显示另一个图像
【发布时间】:2011-11-03 15:41:19
【问题描述】:

我想知道是否有人可以帮助我处理我用于 Jquery Nivo 幻灯片的这个 PHP 脚本。该脚本从文本文件中获取文件名,并根据您所在的页面通过分页显示它们。

如果文件不存在,脚本是否可以显示另一个图像?比如image1.jpg在images/work/目录下不存在,那么会显示图片不可用.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>
"?>

【问题讨论】:

标签: php slider nivo-slider


【解决方案1】:
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() 结合了两者,只有当文件存在 并且 可以被网络服务器访问时才会返回 true。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      你需要file_exists();

      返回一个布尔值。在 if 语句中使用它。前提是您具有访问图像的适当权限。

      【讨论】:

        猜你喜欢
        • 2015-03-16
        • 2012-07-23
        • 1970-01-01
        • 2018-03-16
        • 1970-01-01
        • 2012-01-27
        • 2016-04-11
        • 1970-01-01
        相关资源
        最近更新 更多