Why won't this code work?

泄露秘密 提交于 2019-12-25 17:38:08

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/1025065/why-wont-this-code-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!