Home » Php » php – Check where request came from

php – Check where request came from

Posted by: admin July 12, 2020 Leave a comment


on the site when an image is required the link is like this

<img src="getimage.php?id=<?php echo $name ?>" " width="280px" height="70px">

Then on getimage.php it gets the id and from that finds the right picture and displays it.

$id = $_GET['id'];

This works perfectly. How would I find out where the request came from. So on which page this line below was on

<img src="getimage.php?id=<?php echo $name ?>" "width="280px" height="70px">

So ultimately I can know if the image requested is for index.php or about.php etc


How to&Answers:

You can add an additional parameter to the image URL that specifies from which page it was requested:

<img src="getimage.php?id=<?php echo urlencode($name); ?>&page=<?php echo urlencode($page); ?>" "width="280px" height="70px">

Works exactly like how you did it with the id parameter.

The benefit is, this does not rely on some headers browsers send (or not) like the HTTP Referer, something you have no control over from server-side.

To obtain the page the image-link is generated on, you can use something like this:

$page = basename(__FILE__);

See basename PHP Manual and __FILE__ PHP Manual.

Additionally, the code makes use of the urlencode PHP Manual function to ensure that the attribute doesn’t break.


If set, look for the key HTTP_REFERER in the $_SERVER array:


The address of the page (if any) which referred the user agent to the
current page. This is set by the user agent. Not all user agents will
set this, and some provide the ability to modify HTTP_REFERER as a
feature. In short, it cannot really be trusted. (source)



is that what are you looking for?


You could check out $_SERVER[‘HTTP_REFERER’], but this is not always set by the browser that’s sending the request. You could also set a session variable when sending back a response with a page identifier (ie. ‘about’). If this session variable is set, the previous page requested is in the variable. If it’s not set, the user just landed on your website for the first time in the session.


You have to add another parameter defining the source:

<img src="getimage.php?id=<?php echo $name ?>&amp;src=about" "width="280px" height="70px">

In your PHP script you now can use $_REQUEST[‘src’] to distinguish between the different sources.

Don’t use the referer since it is not reliable.