Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining Referer in PHP

What is the most reliable and secure way to determine what page either sent, or called (via AJAX), the current page. I don't want to use the $_SERVER['HTTP_REFERER'], because of the (lack of) reliability, and I need the page being called to only come from requests originating on my site.

Edit: I am looking to verify that a script that preforms a series of actions is being called from a page on my website.

like image 615
UnkwnTech Avatar asked Oct 03 '08 07:10

UnkwnTech


People also ask

How do I find the IP address of a referrer?

You can determine the reffering URL with $_SERVER['HTTP_REFERER'] but bear in mind this can be manipulated. You can then use gethostbyname($referrer) to get the IP address.


2 Answers

The REFERER is sent by the client's browser as part of the HTTP protocol, and is therefore unreliable indeed. It might not be there, it might be forged, you just can't trust it if it's for security reasons.

If you want to verify if a request is coming from your site, well you can't, but you can verify the user has been to your site and/or is authenticated. Cookies are sent in AJAX requests so you can rely on that.

like image 161
Seldaek Avatar answered Sep 26 '22 15:09

Seldaek


What I have found best is a CSRF token and save it in the session for links where you need to verify the referrer.

So if you are generating a FB callback then it would look something like this:

$token = uniqid(mt_rand(), TRUE); $_SESSION['token'] = $token; $url = "http://example.com/index.php?token={$token}"; 

Then the index.php will look like this:

if(empty($_GET['token']) || $_GET['token'] !== $_SESSION['token']) {     show_404(); }   //Continue with the rest of code 

I do know of secure sites that do the equivalent of this for all their secure pages.

like image 44
We0 Avatar answered Sep 24 '22 15:09

We0