开发者

PHP image file call origination

I have a file called image.php and one called index.html.

This code is in开发者_开发百科 index.html

<img src="image.php"> 

Now, is it possible for the image.php file to know that it was called by the index.html file ?

If so, how?


The browser will usually send a "Referer" (sic) header for image requests which contain the URL of the page that containing the image link.

This is accessible using the $_SERVER['HTTP_REFERER'] variable (note unusual spelling).

Note that this variable is not always accurate; a user may elect to protect their privacy by not sending a referer header (using some sort of dinky privacy tool) and they may even modify their browser to send whatever they want in this field. So it shouldn't be relied upon for authentication, unless you also take into account that even a legitimate user may have left it blank or put an arbitrary string in it.


A more reliable (albeit more convoluted) way of doing this is to generate a random hash to attach to this specific load of the file - but this is only going to work if the originating page is also php enabled (not just static html).

If you wanted to do it that way, you could do something like this:

<?
// index.php or wherever you want to detect the source from
session_start();
$uniqid = uniqid();
$_SESSION["image_caller_$uniqid"] = $_SERVER['SCRIPT_FILENAME'];
echo "<img src='image.php?uniqid=$uniqid' />";
?>

And then in your image file

<?
// image.php
session_start();
$source = $_SESSION["image_caller_{$_GET['uniqid']}"];
unset($_SESSION["image_caller_{$_GET['uniqid']}"]); // Don't needlessly waste memory
// Render the image or whatever you want here
?>

This has the similar effect as other suggestions of doing something like <img src='image.php?ref=index.html'>, however this is much more difficult to spoof.


If the user is using a browser that sends a referrer header, you can access it with

$_SERVER['HTTP_REFERER']

but it relies on the client being trustworthy, which you can't count on.

If you want a browser independent method, you can add a GET parameter to your link

<img src="image.php?ref=index.html">

and access with $_REQUEST['ref'], but again, it can be spoofed.


Only if you're willing to trust some extremely unreliable data found in $_SERVER.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜