How I can get origin of request with PHP? How I can get origin of request with PHP? ajax ajax

How I can get origin of request with PHP?


According to the article HTTP access control (CORS) by MDN:

All requests must be set Origin header to work correctly under CORS(Cross-origin resource sharing) mechanism.

The "Origin" request header is part of RFC 6454 and describes it as part of CORS mechanism and is compatible with all browsers according to MDN.

Description by MDN:

The Origin request header indicates where a fetch originates from. Itdoesn't include any path information, but only the server name. It issent with CORS requests, as well as with POST requests. It is similarto the Referer header, but, unlike this header, it doesn't disclosethe whole path.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin

Example by MDN:enter image description here

So, to get origin of the XHR request with PHP you can use:

$_SERVER['HTTP_ORIGIN'] 

And, in the case of a direct request, you can combine HTTP_REFERER and REMOTE_ADDR like:

if (array_key_exists('HTTP_REFERER', $_SERVER)) {    $origin = $_SERVER['HTTP_REFERER'];} else {    $origin = $_SERVER['REMOTE_ADDR'];}

So, the possible final solution is:

if (array_key_exists('HTTP_ORIGIN', $_SERVER)) {    $origin = $_SERVER['HTTP_ORIGIN'];}else if (array_key_exists('HTTP_REFERER', $_SERVER)) {    $origin = $_SERVER['HTTP_REFERER'];} else {    $origin = $_SERVER['REMOTE_ADDR'];}

MDN is Mozilla Developer Network.

Thanks a lot for help @trine, @waseem-bashir, @p0lt10n, and others persons.


in php you can get using $_SERVER['HTTP_REFERER'].if you are using codeigniter then you can get the referrer using $this->agent->is_referral().


$_SERVER['HTTP_ORIGIN']  // HTTP Origin header$_SERVER['HTTP_HOST']    // HTTP Host header$_SERVER['HTTP_REFERER'] // HTTP Referer header$_SERVER['REMOTE_ADDR']  // HTTP Client's Public IP

Let's discuss above $_SERVER parameters.

First, XHR is at client side and it bounds with a http client. As Origin and Referer headers are not mandatory, a client other than standard web browser will not set that. Next Host header may not be mandatory. If your REST server uses virtual hosts, this header is a must to route requests correctly. But this header doesn't have any detail about the client. Only unique thing for http client is Public IP. But this corresponds to many clients as ISP's use network address translations or proxies.

Since everything is relative and within bounds, CORS like mechanisms are built on HTTP Origin header. Clients are assumed and advised to be using standard browsers.

In your case, my opinion is it's OK to depend on Origin header. You can implement CORS mechanism if it suits for you.