Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get http request origin in php

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

like image 875
m_junior Avatar asked Aug 27 '14 06:08

m_junior


People also ask

How do I get the HTTP origin in PHP?

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.

How do I find the origin of a request?

The origin is determined by the URL of the HTML document, not the script. If I'm wrong then how do I determine who is the origin of an HTTP request? A cross-origin request from XHR or Fetch will include an Origin HTTP request header.

What is origin in HTTP request?

The Origin request header indicates the origin (scheme, hostname, and port) that caused the request. For example, if a user agent needs to request resources included in a page, or fetched by scripts that it executes, then the origin of the page may be included in the request. Header type.

When Origin header is sent?

In terms of the spec requirements: The spec requires the Origin header to be sent only for any request which the Fetch spec defines as a CORS request: A CORS request is an HTTP request that includes an Origin header.


1 Answers

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

like image 75
hex494D49 Avatar answered Oct 02 '22 05:10

hex494D49