如果存在图像,如何在网页上显示图像.否则使用“默认图像”


How can I display an image on webpage if it exists...else use "default image"?

ok...这是我第三次尝试解决这个问题。 希望这次我说得更清楚一点。 我有一个包含各种不同图像的文件夹。

文件夹名称为:"../wp-content/gallery/playerphotos/'

文件名按以下方式传递:

$photoname = $row['First_Name'] . " " . $row['Last_Name'];

如果匹配的文件存在,我想显示照片(".jpg"(。

如果该文件不存在,则使用同一文件夹中的默认照片: '../wp-content/gallery/playerphotos/NoPhotoAvailable.jpg'

我期待听到你的建议。 谢谢你的时间。

我有一个更棘手的解决方案。与其每次想要提供照片时都调用file_exists()(可能最小的(开销,不如让 PHP 输出照片名称,就好像它存在一样(例如:../wp-content/gallery/playerphotos/Jack Sample.jpg(。然后编写一个小的 .htaccess 规则(如果您使用的是 Apache(,将playerphotos目录的 404 文件设置为NoPhotoAvailable.jpg。如果您不使用 Apache,则可能会对服务器使用类似的规则,但这里的优点是,虽然它不是 100% 可移植的,但它将检查文件是否存在的工作交给了优化为提供文件的程序。使用 apache,您需要这样的规则:

<Directory /path/to/www/wp-content/gallery/playerphotos>
    ErrorDocument 404 /wp-content/gallery/NoPhotoAvailable.jpg
</Directory>

您可以使用以下 PHP 函数来检查文件名(在您的示例中为 $photoname(是否存在:

bool file_exists ( string $filename )

查看以下页面中的文档:

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

一个

更棘手的解决方案怎么样? :)

$photoname = (file_exists($row['First_Name']." ".$row['Last_Name']))?($row['First_Name']." ".$row['Last_Name']):("../wp-content/gallery/playerphotos/NoPhotoAvailable.jpg")

然后你只需添加一个图像标签

<img src="<?php echo $photoname; ?>" />

您将需要使用 PHP 函数 file_exists 它接受一个参数作为文件名。

您将首先检查服务器上是否存在该文件。如果没有,则将照片名称设置为默认名称。

if(!file_exists($photoname)) {
    $photoname = '../wp-content/gallery/playerphotos/NoPhotoAvailable.jpg';
}