...

View Full Version : Coding for 404 images..



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

rick_james.jpg
michael_jackson.jpg
barbara_streisand.jpg
prince.jpg
stevie_ray_vaughn.jpg

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.

Thanks!

mem0ri
01-17-2008, 08: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.

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



$images = array(
"rick_james.jpg",
"michael_jackson.jpg",
.
.
.
);
if(!in_array($name, $images)) {
$name = "no-pic";
}


or even a switch / case statement



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum