Qué método usar cuando una imagen no existe

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) Usa 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 evento

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?

preguntado el 09 de marzo de 12 a las 15:03

I'd go with method 2 using javascript because it's completely handled on the client side and frees processing resources from the server. I wouldn't use ajax, because if you're going to use javascript and run the risk of a delay in displaying the image, you might as well use the simple approach. Using the tag with a background image guarantees that both images are loaded each time, even if only one will be displayed. In situations where the background image loads first due to latency issues, it could end up "flickering". -

@GigaWatt: good point there about loading of both image and background. -

5 Respuestas

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 src attribute (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 cada image on the page). If you want to do this, consider having a task which runs on a cron which does this for you.

En definitiva, tu no debe be in an environment where images are becoming unavailable so often.

respondido 09 mar '12, 16:03

Points taken. Let me get a few more answers. - Desbordamiento de preguntas

5) setup your web-server to show default image, involving no PHP at all. Something like

<directory /images>
ErrorDocument 404 /images/default.jpg
</directory> 

respondido 09 mar '12, 16:03

Hi Colonel Shrapnel, I can understand the answers given by others, but your one requires further elaboration. Does it work if I have to show different default images based on different scenarios? - Desbordamiento de preguntas

we use nginx to serve static content like images, css and javascript. there we configure error_page 404 /path_to_some_php_script that handle all requests to missing files. error_page directive work like this: when you request some content nginx checks that the requested resource exists. if it doesnt it redirects to the url specified. then you can parse the url and make some conditionals so you can display different type/size of default images.

respondido 09 mar '12, 16:03

Does it work if I have to show different default images based on different scenarios? - Desbordamiento de preguntas

it's all in your hands to write the handler ... generally you might do what you want. just play with the url .... - Plamen Paskov

you can use either JS

<img src='earth.jpg' onerror='this.src=/somewhereovertherainbow.jpg' />

respondido 09 mar '12, 16:03

Puedes eliminar <img /> tag with jQuery if referenced image does not exist:

<img src="image.png" onerror="$(this).remove()" />

o bien:

<script>
  $(document).ready(function () {
    $("#img1").error(function () { $(this).remove() });
  });
</script>

<img id="img1" src="image.png" />

Respondido 15 Abr '13, 13:04

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.