2

When trying to display image that's adress doesn't exist you will see default browsers "no image" badge.

How to change it to default "no-image.png" placeholder?

echo "<img src='http://www.google.com/trolol.png'>"; //for example 
0

5 Answers 5

18

You can use the onerror attribute, example:

<img src="" onerror="this.src = 'no-image.png';" alt="" /> 

Demo: http://jsfiddle.net/kNgYK/

Sign up to request clarification or add additional context in comments.

2 Comments

OK why this fails: <?php $error = "onerror='this.src = \'http://userlogos.org/files/logos/pek/stackoverflow2.png\'';"; for ($i = 1; $i <= 10; $i++) { echo "<img src='http://services.runescape.com/m=itemdb_rs/3716_obj_sprite.gif?id=" . $i . "' alt='ID " . $i . "' title='ID " . $i . "'" . $error . "/>"; } ?>?
Neat solution, better than the accepted one imo :) Thnx!
5
<img src='http://www.google.com/trolol.png' onerror="this.src='http://jsfiddle.net/img/logo.png'">​ 

sample http://jsfiddle.net/UPdZh/1/

The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).

Syntax

<element onerror="SomeJavaScriptCode"> 

http://wap.w3schools.com/jsref/event_onerror.asp

Comments

1
<?php $filename = 'http://www.google.com/trolol.png'; if (file_exists($filename)) { echo "<img src='".$filename."'>"; } else { echo "<img src='no-image.png'>"; } ?> 

2 Comments

OK WTF why it fails, when your code not: <?php $i = 2; $filename = "http://services.runescape.com/m=itemdb_rs/3716_obj_sprite.gif?id=" . $i; if (file_exists($filename)) { echo "<img src=" . $filename . " />"; } else { echo "NO IMAGE"; } ?>
Just forgot your ' ' :) <?php $i = 2; $filename = "services.runescape.com/m=itemdb_rs/3716_obj_sprite.gif?id=" . $i; if (file_exists($filename)) { echo "<img src='" . $filename . "' />"; } else { echo "NO IMAGE"; } ?>
0

Try this

<?php $filename = 'http://www.google.com/trolol.png'; if (file_exists($filename)) { echo "The file $filename exists"; } else { echo "The file $filename does not exist"; } ?> 

2 Comments

This code fails, have you tried it on remote file like "google.pl/logos/2012/haring-12-hp.png"?
hi this one will work. <? // Set the URL you want to connect to $url = "img2.meetupstatic.com/906521611995523788/img/header/logo.png"; // Check to see if the file exists by trying to open it for read only if (fopen($url, "r")) { echo "File Exists"; } else { echo "Can't Connect to File"; } ?>
0

As you asked for a PHP solution:

if (file_exists($filename)) { echo "i_exist.jpg"; } else { echo "fallback.jpg"; } 

IMPORTANT: Works only for local files, not for remote ones! Thanks to Szymon for the comment!

2 Comments

by the way the (fantastic) onerror="..." solution can kill older versions of opera.
This code fails, have you tried it on remote file like "google.pl/logos/2012/haring-12-hp.png"?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.