Moozoo
Moozoo

Reputation: 497

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

I was wondering if someone would be able to help me out with this PHP script I am using for a Jquery Nivo slideshow. The script gets filenames from a text file, and displays them according to the page you are on through pagination.

Is there a way for the script to display another image if the file doesn't exist? For example, if image1.jpg doesn't exist in the images/work/ directory, then the image unavailable.jpg will display instead?

The script:

 <?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>
"?>

Upvotes: 0

Views: 3319

Answers (3)

Mob
Mob

Reputation: 11096

You need file_exists();

Returns a boolean. Use it in an if statement. Provided you have proper permissions to access the images.

Upvotes: 1

Marc B
Marc B

Reputation: 360732

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
}

Note that I've used is_readable() - some people may suggest using file_exists(), but that can return a false positive: the file may exist, but still can't be read due to a permissions issue. is_readable() combines both and will only return true if the file exists AND can be accessed by the webserver.

Upvotes: 4

Polynomial
Polynomial

Reputation: 28316

You could use file_exists() if it's on your server. It takes a path to the file as an argument, not a URL.

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

Upvotes: 1

Related Questions