How to get http request origin in php

68,645

Solution 1

Use $_SERVER['HTTP_REFERER']. It is 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.

For further restrictions you can perform the following. example.com should be changed to your domain.

IIS set below in web config:

add name="Access-Control-Allow-Origin" value="http://www.example.com"

Apache set below in httpd.conf/apache.conf

Header add Access-Control-Allow-Origin "http://www.example.com"

Solution 2

Generally, this header should do the job. Having the domain name in this header

header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN'] . "");
// use domain name instead of $_SERVER['HTTP_ORIGIN'] above

but if you want to check for more info, use something like the following snippet

$allowed = array('domain1', 'domain2', 'domain3'); 

if(isset($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'], $allowed)){
    // SELECT credentials for this user account from database
    if(isset($_GET['api_key'], $_GET['app_secret'])
        && $_GET['api_key'] == 'api_key_from_db' 
        && $_GET['app_secret'] == 'app_secret_from_db'
    ){
        // all fine
    }else{
        // not allowed
    }
}else{
    // not allowed
}

If the users have to pass more data to your service, use POST instead of GET

Solution 3

Laravel 5: in request method controller:

$origin = request()->headers->get('origin');

Solution 4

Technically neither origin nor referer are required HTTP headers, all of these answers are based on specific browser headers sent, and basing your system on different behaviors of clients is a bad idea.

The correct answer is you can't reliably get the client origin on every request because it isn't required as part of the HTTP specification.

Solution 5

Using a var_dump you can see all that the request has to offer.

var_dump($_REQUEST);

Do a var_dump on the server global as well. It contains alot of usefull information.

var_dump($_SERVER);
Share:
68,645

Related videos on Youtube

m_junior
Author by

m_junior

Updated on July 14, 2022

Comments

  • m_junior
    m_junior almost 2 years

    I want to create an API, and to authenticate API consumers, I will provide an API KEY, App-id and App-Secret. The problem is that I want to know where the http Request is coming from, so that I can know if the Host that is making que request is the registered Host. For example : www.someone.com has an app-id :0001, app-secret:1200 and api-key:458. If this credentials are used to make A request, I want to know if the requester is really www.someone.com

    • hex494D49
      hex494D49 over 9 years
      For origin use this header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN'] . ""); and then check credentials from GET or POST variable
    • PeeHaa
      PeeHaa over 9 years
      Using the origin as a security measure is beyond useless. This header can easily be faked. Instead you might want to work with a callback to pass some "request token" (think about how the oauth flow works).
    • rogerdpack
      rogerdpack about 7 years
      Using HTTP_ORIGIN or HTTP_REFERER without checking them is "in essence" the same as doing "*" which can open up subtle security holes so is discouraged, see stackoverflow.com/questions/12001269/…
    • Martin Schneider
      Martin Schneider almost 7 years
      An answer to the actual question "How to get http request origin" can be found here: stackoverflow.com/questions/41326257/…
  • m_junior
    m_junior over 9 years
    If the $_SERVER['REMOTE_ADDR'] variable returns me the Client_IP and not the website address, How am I supposed to autheticate the website??
  • hex494D49
    hex494D49 over 9 years
    @m_junior $_SERVER['REMOTE_ADDR'] returns the IP address of the server under which the current script is executing.
  • hex494D49
    hex494D49 over 9 years
    @m_junior The $allowed array from above may look even this way $allowed = array('domain1' => '1.2.3.4', 'domain2' => '5.6.7.8', 'domain3' => '2.4.6.8'); and then you can use gethostbyname('domain') and compare returned IP of the host with the IP in your array.
  • m_junior
    m_junior over 9 years
    Does it mean that If an website has a javascript that makes a post to my API, once I receive the request the $_SERVER['REMOTE_ADDR'] WILL be filled with the website IP and not the client IP??? sorry for the ignorance level!
  • hex494D49
    hex494D49 over 9 years
    @m_junior No worries, feel free to ask :) If you need the IP of the host (where the website is hosted) use gethostbyname('www.your-client.com') but if you need the IP of the computer from where the request came from, use $_SERVER['REMOTE_ADDR']
  • Daniel W.
    Daniel W. almost 8 years
    Instead of putting every possible origin in, which is bad by default, you could also use *, which is not better. This answer introduces a security problem.
  • Daniel W.
    Daniel W. almost 8 years
    The referrer and the origin are two different things.
  • hex494D49
    hex494D49 almost 8 years
    @DanFromGermany Pointing to something that might seem to you wrong and at the same time not providing any other, maybe a better solution, is by default a very bad, selfish and even childish attitude.
  • Mike Willis
    Mike Willis over 7 years
    @DanFromGermany how is having a white-list of permitted origins a bad thing?
  • LeonanCarvalho
    LeonanCarvalho over 7 years
    getallheaders(); doen't exist in php-fpm or php-fastcgi
  • LeonanCarvalho
    LeonanCarvalho over 7 years
    Not all user webservers will set this, and some provide the ability to modify HTTP_ORIGIN as a feature. In short, it cannot really be trusted.
  • LeonanCarvalho
    LeonanCarvalho over 7 years
    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.
  • sensadrome
    sensadrome over 7 years
    Yes this is why I mentioned that is was assuming you were using php as a module (mod_php) and that otherwise its available as an environment variable.
  • Martin Schneider
    Martin Schneider almost 7 years
    @DanFromGermany @LeonanCarvalho : Access-Control-Allow-Origin header doesn't introduce a security problem. There is no difference in security on the server side if that header is set ot not. This header is only there for adding security on the end-user-side. So no malicous website may use your API and receive user session data (cookies). And this only if the user is using a common browser that listens for this header and hasn't been manipulated (by virus etc). To secure the server side, other measures must be taken.
  • Martin Schneider
    Martin Schneider almost 7 years
    Anyway it is better to only set header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN'] . ""); within the first if statement.
  • Martin Schneider
    Martin Schneider almost 7 years
    A better answer to that question can be found here: stackoverflow.com/questions/41326257/…
  • Martin Schneider
    Martin Schneider almost 7 years
    @hex494D49 why do you rejected my edit? Your code has 4 syntax errors and isn't optimal formatted for SO.
  • Daniel W.
    Daniel W. almost 7 years
    I am not sure anymore what happened when I commented like a year ago. Important is the array $allowed and that makes it a good answer.
  • hex494D49
    hex494D49 almost 7 years
    @MA-Maddin As a reason for editing, you mentioned "improved formatting" and you didn't mention any syntax errors. I personally don't like spaces after each keyword, so I thought your editing actually isn't an improvement. But since you're right about syntax errors, I left them so you can correct them (again) and I'll accept your edit. Sorry and thanks :)
  • SteJ
    SteJ about 6 years
    As @DanFromGermany touched on, ORIGIN and REFERER are two different things - HTTP_ORIGIN is the better in this case than HTTP_REFERER; if HTTP_ORIGIN is missing then you may wish to fall back to using HTTP_REFERER, but I would advise against this for security (it's easier to change the referer than the origin, as origin is listed as a "forbidden" header and browsers should prevent any changes to origin from taking place).
  • hex494D49
    hex494D49 almost 6 years
    @DanFromGermany Just wanted to thank you for your last comment :)
  • Rotimi
    Rotimi over 5 years
    I have a question. Can't the HTTP_ORIGIN value be spoofed/faked?
  • Kamil Kiełczewski
    Kamil Kiełczewski about 5 years
    to get all headers: request()->headers->all();
  • MaXi32
    MaXi32 over 4 years
    I use this one on my front end server and I forgot to remove it and the server got hacked. Very dangerous for a lot 'useful information'
  • alev
    alev over 4 years
    Can't an unauthorized person simply change the request headers in his client to send a domain of an authorized domain and this way circumvent the check?
  • alev
    alev over 4 years
    I just found the answer on a different thread: stackoverflow.com/a/21058346/4688612
  • Vit
    Vit about 4 years
    first check it with request()->headers; then you can add "->get(' ..needed parameter.. ');"
  • mangusta
    mangusta almost 4 years
    origin is not sent with GET
  • Kamil Kiełczewski
    Kamil Kiełczewski almost 4 years
    @mangusta browser add origin header for CORS requests - more here - if you don't send CORS request then browser not add this header and probably php not set it too (or probably set some default value - but I don't check this on php side ).