I am currently using the php file_exist method to check if an image exist and to display the default image if it doesn’t:
if(file_exists($image_location))
{
echo "<img src='$image_location'>";
}
else
{
echo "<img src='default_image.jpg'>";
}
Other than doing the above, I know that can:
1) Style the <img> tag with a background image
2) Use javascript onerror method to replace the missing image
If the image is hosted remotely,
3) Generate a HEAD request using cURL to detect the presence of the image or
4) Use the jquery ajaxComplete event
I think each method has its advantages and disadvantages. My long-term intention is to host the image separately, so all four options should be feasible. But which would be the better one and why?
A
file_exists()check for each image on each page requests sounds extremely over-the-top; is your environment that unstable!?#1 and #2 sound like your best bet. Out of those 2, I’d choose #2 as a background image has different behaviour to the
srcattribute (e.g. how the image is resized/ repeated if it doesn’t fit within the image bounds).Be sure do avoid doing #3 for each image for each request; you’ll slow down your page load infinitely (making a HTTP connection for each image on the page). If you want to do this, consider having a task which runs on a cron which does this for you.
Ultimately, you shouldn’t be in an environment where images are becoming unavailable so often.