Reputation: 187
Is it possible to block a php script from running in a img src
tag?
I don't want the script from http://example.com/page.php to be executed if is called on a webpage in this way:
<img src="http://example.com/page.php">
I want it to run only if the page is opened directly or if a user clicks on a link from that page, so blocking the referrer is not a solution.
Upvotes: 0
Views: 394
Reputation: 53255
Yeah, it is possible to do this using the accept header, but the protection can be bypassed by individual user. When browser is downloading an image, it sends headers what data are expected - for example Accept: image/png,image/*;q=0.8,*/*;q=0.5
But this can not be relied on of course, as any user may turn this header off and any browser can happen not to send this header.
Here, you can read article about compatibility of http Accept header.
Another useful header may be the Referer
header. This header tells you the site that invoked this request (image on that site, CSS on the site or just link followed from this site). The rules are the same - most users will send the header, but some may turn it off.
Many people has installed plugin to block referrer header to increase their privacy.
Upvotes: 1
Reputation: 10033
I did a little testing. It seems like Firefox and IE will stop waiting for a complete reply if you flush the content-type as text/html (and probably anything other then an image). But I could not see that they disconnected. Chrome however waited for the whole page.
So it seems like you will have to render the whole page anyway if the browsers do not disconnect or if PHP can not detect it. And you will have to decide on all the header settings very early. So this is not worth it.
frametest.html
<html>
<head>
<title>Frame test</title>
</head>
<body>
<h1>Frame test</h1>
<p>The following frame is not to be displayed in frames!</p>
<img src="frametest.php"/>
</body>
</html>
frametest.php
<?php
header('Content-Type: text/html');
echo " ";
flush();
sleep(3);
echo " \r\n ";
flush();
$aborted = (connection_aborted() ? 'yes' : 'no');
$status = (connection_status() ? 'yes' : 'no');
$temp = mail('[email protected]', 'Frametest', 'Client Aborted: ' . $aborted . ' Status: ' . $status);
?>
<html>
<head>
<title>test</title>
</head>
<body>
<h1>Test</h1>
<p>Not to be displayed in frames!</p>
<p>Mail ok? <?php echo ($temp ? 'Yes' : 'No'); ?> </p>
</body>
</html>
Upvotes: 0
Reputation: 13283
No. There is no way to block a PHP script from running in an image tag.
Once the script is run you can, however, send back different content depending on the headers. Because headers can be modified this is not a reliable way of preventing anything.
It should not be a problem, though, that a script is run in an img
tag. Once the browser sees that the content is not an image it will simply discard it and not do anything (or it may show an error of some sort).
Upvotes: 0