PHP Image Check

Introduction.

This page uses PHP to check if an image exists before displaying. If it is not found, a default image is displayed instead, and a message is tagged on to the end of the alt text.

In this example, the first requested image exists, and should display correctly. The second requested image does not exist, so should be replaced by the default image.


In Action.

filename set to: "images/pendragon.jpg".
alt set to "Pendragon live at Rotherham Oakwood Centre".
About to check image.
Image check passed.
About to display image: images/pendragon.jpg
Pendragon live at Rotherham Oakwood Centre

filename set to: "images/noSuchPicture.jpg".
alt set to "A non-existant image".
About to check image.
ERROR: Image check failed. Using default image instead and appending message to alt text.
About to display image: images/altImage.jpg
A non-existant image [Image not found. Replaced by default image]

To demonstrate how this might work within HTML code, imagine you want to reference an image using <img src="blah.jpg" alt="blah"> but you can't always be sure it will be there. PHP is easy enough to integrate into HTML code, so here are the 2 images in the test above. First, is the picture of Pendragon, Pendragon live at Rotherham and now here is the attempt at the other image, A non-existent picture [Image not found. Replaced by default image]


The Code!

This is the PHP code that performs the above.

<?php
function showImg($filename, $alt) {
    $defaultImg="images/altImage.jpg";
    print("<p>filename set to: \"$filename\".<br> alt set to \"$alt\".<br> About to check image.<br>\n");
    if(!file_exists($filename)) {
        print("<span style=\"color:red; font-weight: bold\">ERROR: </span>Image check failed. Using default image instead and appending message to alt text.<br>\n");
        $filename = $defaultImg;
        $alt = "$alt [Image not found. Replaced by default image]";
    }
    else {
        print("Image check passed.<br>");
    }
    print("About to display image: $filename<br>");
    print("<img src=\"$filename\" alt=\"$alt\"></p>\n");
}

$img1="images/pendragon.jpg";
$alt1="Pendragon live at Rotherham Oakwood Centre";

$img2="images/noSuchPicture.jpg";
$alt2="A non-existant image";

showImg($img1, $alt1);
showImg($img2, $alt2);

?>


Nigenet Home | Email me