Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get domain of a POST request

Tags:

ajax

post

php

I have a script that makes a POST request to my website from other websites (different domains) and I need to know if it's possible to get what's that other domain.

Like: helloworld.com uses my script and it executes a POST request with mywebsite.com. How does mywebsite.com know that the request is from helloworld.com?

I have tried with $_SERVER['REMOTE_HOST'] but that's not working.

like image 494
Ryan Casas Avatar asked Dec 11 '25 09:12

Ryan Casas


2 Answers

You need to inspect the HTTP referrer.

In PHP this would be $_SERVER['HTTP_REFERER'];.

In JavaScript, this would be document.referrer.

Note that it can be inaccurate and is easy to be spoofed, so it's value should be taken with a pinch of salt.


To provide a little bit more detail on how you can do this reliably (albeit with the cooperation of the remote server):

  1. Let secret be a arbitrary string (abc123).
  2. Let key be a random string which is unique to each request (e.g. the current time)
  3. Generate token by md5(secret + key).
  4. Have the remote server include key and token (but not secret) in the POST request.
  5. On your server, ensure that md5(secret + key) === token

Because no-one knows the secret, you can guarantee that the request originated from the remote server. Of course, it's then possible for someone to request the form from the remote server, steal the key and token, and then forward the request to yourself...

like image 161
Matt Avatar answered Dec 12 '25 21:12

Matt


You should use HTTP_REFERER. But it can not be trusted fully

$_SERVER['HTTP_REFERER']

Take a look here, where it is documented: http://php.net/manual/en/reserved.variables.server.php

like image 43
Rene Pot Avatar answered Dec 12 '25 21:12

Rene Pot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!