tags:

views:

250

answers:

4

Can anyone tell me why this code won't work?

<?php $err=1; ?>

<img src="334234234234234.gif" onError="<?php $err=0; ?>" />

<?php echo "<br />" . $err; ?>

Even when the image exists, the onerror is still executed. Why?

+11  A: 

HTML cannot set PHP variables. Those can only be set while on the server. The onError method of the IMG tag has no access to PHP variables.

The page life-cycle:

  1. (SERVER) The server builds your page (handling variables, etc)
  2. (SERVER -> CLIENT) The server sends out the page to the client computer
  3. (CLIENT) The html is loaded, javascript is ran, and any errors are raised.

Note, you're attempting to combine item 3 with item 1, which cannot be done semantically.

The only way to do what you're attempting would be to attach a javascript method to that event, and communicate to the server when and if the onError method is ran. But this is likely going to be a bit more complicated than you're use to.

Jonathan Sampson
+4  A: 

Since php is server side code, the <?php $err=0; ?> will get executed whether or not onError actually happens. You'll want to use someother method, or Javascript (or another client side code) to do that.

If all you are wanting to do is print out a variable to the screen if the image doesn't load, you can use onError="alert('ERROR: Image did not load');" to create a popup box (or you can use javascript to modify the html on the page), but if you want to talk to the server, you'll have to either submit a form with javascript or use an AJAX method.

DeadHead
+3  A: 

Your code will always produce this output:

<img src="334234234234234.gif" onError="" />
<br />0

The onError JavaScript handler is empty because the php code inside it produces no output.

Is the code you posted actual code or simplified code? It's not clear what you're trying to accomplish.

artlung
no. the php code inside onError will always be executed as the above 2 answers said.
giolicious
The php code *is* executed, on the server, and the onError handler will *always* be empty, as I said.
artlung
+2  A: 

If you are checking for the existence of a file PHP offers a nice function

http://us.php.net/file_exists

Modified example from page.

<?php
$filename = '/path/to/334234234234234.gif';

if (file_exists($filename)) {
    echo "<img src='334234234234234.gif'/>";
} else {
    echo "The file $filename does not exist";
}
?>

To answer your question.

Even when the image exists, the onerror is still executed. Why?

The onError is never executed. It appears to execute because you explicitly output the $err variable at the end of the script. If you use the above code you can achieve what I believe was the intended result without relying on a JavaScript event.

Cranium Slows