4

I have a page which displays lots of images from different remote servers. http://example.com/img/email_star0.png' height='150' />

Now suppose this image is not present, I get a (x) in my html. Is there anyway that I can detect that this image is not present and replace this (x) with a local image without having to check if the file exists on the remote server using Curl (or using JQuery for that matter) and thereby save time? Can this be done locally?

Thanks for your help

Waqleh
  • 9,741
  • 8
  • 65
  • 103
user1038814
  • 9,337
  • 18
  • 65
  • 86
  • so there is no way of detecting if the image is available (on the server side) and if it is not, replace it with the local image? – ppp Jan 18 '12 at 13:34
  • @David What would be a valid php way to do that check? – ppp Jan 18 '12 at 13:38

3 Answers3

22

Yes this is possible using onerror event:

<img src="your_image_source" onerror="this.src='/path/to/local/file'">

If the image does not exist, instead of displaying the X, this will show the default image in your local folder

Ninja
  • 5,082
  • 6
  • 37
  • 59
3

I don't think it is possible to check if image exists on remote server without using curl or jQuery. But jQuery snippet bellow reacts on image loading error by replacing it with a local one, maybe that's what you are looking for.

$(document).ready(function(){
  $('img').error(function(){
     $(this).attr('src', 'http://mysite/myimage.jpg');
  });
});
Konrad Dzwinel
  • 36,825
  • 12
  • 98
  • 105
3

You can use the 'onerror' attribute directly in the image tag:

<img src="my_images.jpg" onerror="this.src='my_replacement.jpg'">
David M
  • 71,481
  • 13
  • 158
  • 186
Metafr
  • 101
  • 9