How to get http request 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.
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"
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
Laravel 5: in request method controller:
$origin = request()->headers->get('origin');