View Full Version : Coding for 404 images..

01-17-2008, 07:04 PM
I have a set of images in my /img folder... for example:


I have a script that uses a variable $name that displays the images listed above.

<img src="/img/<?php echo $name; ?>.gif">

When $name = rick_james, michael_jackson, etc... all is good and it shows the appropriate picture.

BUT say if the variable $name = kenny_loggins, then it throws a 404, saying img/kenny_loggins.gif does not exist.

What is happening is that my server is working overtime trying to display images that do not exist.

How can I write code that fails properly?

in other words, if the image does not exist, don't try to look for it, if it does then go ahead and display it.


01-17-2008, 07:08 PM
You're going to have to run some authentication of the submitted variable. You can do so in multiple ways, but one suggestion is to try something like:

if(!is_file($name.".gif")) // error
else // display image

You will, of course, need to ensure the proper pathing to check for the file's existence (if you check the wrong folder, you'll always return no-file). Those details can be seen at php.net by looking up the is_file function.

Hope that helps.

01-17-2008, 08:44 PM
Or use an array...

$images = array(
if(!in_array($name, $images)) {
$name = "no-pic";

or even a switch / case statement