WP Elite

Wordpress, web design and SEO tips

How to add a default image if image doesn’t exists using PHP?

Have you encountered a project which include images stored on a database and you’ll need to display it, but you’re not sure if this image still exists? What if its a catalog page, you saw one block of image was not displaying because the image is old or you got a wrong image URL. This will really affect the design of the page if one image has a question mark on it or blank. Here’s a simple PHP script that you can use in your loop functions to detect a missing image and set a default image so that it will not ruin the page design.

<?php
function check_image_exists( $url, $default = 'default.jpg' ){
	$url = trim($url);
	$info = @getimagesize($url);
	if( (bool) $info ){
		return $url;
	}else{
		return $default;
	}
}
?>

This function will test if the image exists using getimagesize() function. If the image exists then it should have an information to that image like size, width, height etc. it will return the original image URL. But if the test returns false it will just use the $default variable image which is your default image.

<?php
$test_orig_image = "http://www.example.com/gifs/logo.gif";
$my_deafult_image = "http://www.example.com/default/def.gif";
?>
<!--HTML CODE HERE-->
.
.
.
<img src="<?php echo check_image_exists($test_orig_image, $my_deafult_image); ?>" alt="My Test Image" />

You can even use a custom default image if you want. Just set the second argument of the function and it will override the functions default image(default.jpg).

If you just want to determine the image really exists and you don’t want to set a default image for it, you can also modify the function. Here it is.

<?php
function check_image_exists( $url ){
	$url = trim($url);
	$info = @getimagesize($url);
	return ( (bool) $info );
}
//Usage
$test_orig_image = "http://www.example.com/gifs/logo.gif";
if( check_image_exists( $test_orig_image ) ){
	echo "Image exists!";
}else{
	echo "Not Found!";
}
?>

That’s it! So easy right? You can also use this on your WordPress functions if you’re working with images. I’m sure this will be very useful if you’re working with Shopping Cart or Catalog websites that display lots of images.

Filed Under: Blog

Copyright © 2023 · WPLeet.com