PHP - Redirect based on country
To implement your own ! You have to make a tables of country wise IP addresses ...
Or Simply you can use the following plugin.
If you want to implement a redirect using GeoPlugin (Third Party)
Here is the GeoPlugin config.php file
<?php
class geoPlugin {
//the geoPlugin server
var $host = 'http://www.geoplugin.net/php.gp?ip={IP}&base_currency={CURRENCY}';
//the default base currency
var $currency = 'USD';
//initiate the geoPlugin vars
var $ip = null;
var $city = null;
var $region = null;
var $areaCode = null;
var $dmaCode = null;
var $countryCode = null;
var $countryName = null;
var $continentCode = null;
var $latitude = null;
var $longitude = null;
var $currencyCode = null;
var $currencySymbol = null;
var $currencyConverter = null;
function geoPlugin() {
}
function locate($ip = null) {
global $_SERVER;
if ( is_null( $ip ) ) {
$ip = $_SERVER['REMOTE_ADDR'];
}
$host = str_replace( '{IP}', $ip, $this->host );
$host = str_replace( '{CURRENCY}', $this->currency, $host );
$data = array();
$response = $this->fetch($host);
$data = unserialize($response);
//set the geoPlugin vars
$this->ip = $ip;
$this->city = $data['geoplugin_city'];
$this->region = $data['geoplugin_region'];
$this->areaCode = $data['geoplugin_areaCode'];
$this->dmaCode = $data['geoplugin_dmaCode'];
$this->countryCode = $data['geoplugin_countryCode'];
$this->countryName = $data['geoplugin_countryName'];
$this->continentCode = $data['geoplugin_continentCode'];
$this->latitude = $data['geoplugin_latitude'];
$this->longitude = $data['geoplugin_longitude'];
$this->currencyCode = $data['geoplugin_currencyCode'];
$this->currencySymbol = $data['geoplugin_currencySymbol'];
$this->currencyConverter = $data['geoplugin_currencyConverter'];
}
function fetch($host) {
if ( function_exists('curl_init') ) {
//use cURL to fetch data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'geoPlugin PHP Class v1.0');
$response = curl_exec($ch);
curl_close ($ch);
} else if ( ini_get('allow_url_fopen') ) {
//fall back to fopen()
$response = file_get_contents($host, 'r');
} else {
trigger_error ('geoPlugin class Error: Cannot retrieve data. Either compile PHP with cURL support or enable allow_url_fopen in php.ini ', E_USER_ERROR);
return;
}
return $response;
}
function convert($amount, $float=2, $symbol=true) {
//easily convert amounts to geolocated currency.
if ( !is_numeric($this->currencyConverter) || $this->currencyConverter == 0 ) {
trigger_error('geoPlugin class Notice: currencyConverter has no value.', E_USER_NOTICE);
return $amount;
}
if ( !is_numeric($amount) ) {
trigger_error ('geoPlugin class Warning: The amount passed to geoPlugin::convert is not numeric.', E_USER_WARNING);
return $amount;
}
if ( $symbol === true ) {
return $this->currencySymbol . round( ($amount * $this->currencyConverter), $float );
} else {
return round( ($amount * $this->currencyConverter), $float );
}
}
function nearby($radius=10, $limit=null) {
if ( !is_numeric($this->latitude) || !is_numeric($this->longitude) ) {
trigger_error ('geoPlugin class Warning: Incorrect latitude or longitude values.', E_USER_NOTICE);
return array( array() );
}
$host = "http://www.geoplugin.net/extras/nearby.gp?lat=" . $this->latitude . "&long=" . $this->longitude . "&radius={$radius}";
if ( is_numeric($limit) )
$host .= "&limit={$limit}";
return unserialize( $this->fetch($host) );
}
}
?>
And Here is the code to Validate country.
require_once('config.php'); //The above code
$geoplugin = new geoPlugin();
$geoplugin->locate();
// create a variable for the country code
$var_country_code = $geoplugin->countryCode;
// redirect based on country code:
if ($var_country_code == "OM") {
header('Location: https:www.something.com/ae');
}
else if ($var_country_code == "US") {
header('Location: https://www.something.com/en');
}
}
If you are not sure about your country code Check Here
Redirect users to different domains of the same web application according to their ip address location
You can use GeoIP module - http://nginx.org/en/docs/http/ngx_http_geoip_module.html
In your config create a map like this
map $geoip_country_code $subdomain {
default en;
RU ru;
ES es;
DE de;
}
Then you can redirect, but an actual rule depends on your server-side.
Example:
http {
# ...
map $geoip_country_code $subdomain {
default en;
RU ru;
ES es;
DE de;
}
server {
listen 80;
server_name www.myserver.com;
location / {
rewrite ^ $scheme://$subdomain.myserver.com$request_uri? permanent;
}
}
}
Obviously there should be a config for every subdomain (en.myserver.com
, ru.myserver.com
, ...). It can be one server section for one subdomain or for all of them at once.
server {
server_name en.myserver.com, ru.myserver.com, ...
}
When user visits your http://www.myserver.com/
GeoIP matches its IP, then map
maps country code (let it be 'RU') to a subdomain. After that you have a string with subdomain in your $subdomain
variable. Then you can use that variable as you want. rewrite
makes redirect from current location to $subdomain.myserver.com
which is actually ru.myserver.com
in our example.
default
in map
is for default value, if none from the left side was matched.
Redirect User to different Website Based on Location (IP Address)
I got the solution using "google.loader.ClientLocation"
here is the code for that if somebody needs it.
Check this JSFiddle
http://jsfiddle.net/kvishnudev/7Ut65/1/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Get web visitor's location</title>
<meta name="robots" value="none" />
</head>
<body>
<div id="yourinfo"></div>
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAp04yNttlQq-7b4aZI_jL5hQYPm-xtd00hTQOC0OXpAMO40FHAxQMnH50uBbWoKVHwgpklyirDEregg"></script>
<script type="text/javascript">
var Continent = {"AD":"Europe","AE":"Asia","AF":"Asia","AG":"North America","AI":"North America","AL":"Europe","AM":"Asia","AN":"North America","AO":"Africa","AQ":"Antarctica","AR":"South America","AS":"Australia","AT":"Europe","AU":"Australia","AW":"North America","AZ":"Asia","BA":"Europe","BB":"North America","BD":"Asia","BE":"Europe","BF":"Africa","BG":"Europe","BH":"Asia","BI":"Africa","BJ":"Africa","BM":"North America","BN":"Asia","BO":"South America","BR":"South America","BS":"North America","BT":"Asia","BW":"Africa","BY":"Europe","BZ":"North America","CA":"North America","CC":"Asia","CD":"Africa","CF":"Africa","CG":"Africa","CH":"Europe","CI":"Africa","CK":"Australia","CL":"South America","CM":"Africa","CN":"Asia","CO":"South America","CR":"North America","CU":"North America","CV":"Africa","CX":"Asia","CY":"Asia","CZ":"Europe","DE":"Europe","DJ":"Africa","DK":"Europe","DM":"North America","DO":"North America","DZ":"Africa","EC":"South America","EE":"Europe","EG":"Africa","EH":"Africa","ER":"Africa","ES":"Europe","ET":"Africa","FI":"Europe","FJ":"Australia","FK":"South America","FM":"Australia","FO":"Europe","FR":"Europe","GA":"Africa","GB":"Europe","GD":"North America","GE":"Asia","GF":"South America","GG":"Europe","GH":"Africa","GI":"Europe","GL":"North America","GM":"Africa","GN":"Africa","GP":"North America","GQ":"Africa","GR":"Europe","GS":"Antarctica","GT":"North America","GU":"Australia","GW":"Africa","GY":"South America","HK":"Asia","HN":"North America","HR":"Europe","HT":"North America","HU":"Europe","ID":"Asia","IE":"Europe","IL":"Asia","IM":"Europe","IN":"Asia","IO":"Asia","IQ":"Asia","IR":"Asia","IS":"Europe","IT":"Europe","JE":"Europe","JM":"North America","JO":"Asia","JP":"Asia","KE":"Africa","KG":"Asia","KH":"Asia","KI":"Australia","KM":"Africa","KN":"North America","KP":"Asia","KR":"Asia","KW":"Asia","KY":"North America","KZ":"Asia","LA":"Asia","LB":"Asia","LC":"North America","LI":"Europe","LK":"Asia","LR":"Africa","LS":"Africa","LT":"Europe","LU":"Europe","LV":"Europe","LY":"Africa","MA":"Africa","MC":"Europe","MD":"Europe","ME":"Europe","MG":"Africa","MH":"Australia","MK":"Europe","ML":"Africa","MM":"Asia","MN":"Asia","MO":"Asia","MP":"Australia","MQ":"North America","MR":"Africa","MS":"North America","MT":"Europe","MU":"Africa","MV":"Asia","MW":"Africa","MX":"North America","MY":"Asia","MZ":"Africa","NA":"Africa","NC":"Australia","NE":"Africa","NF":"Australia","NG":"Africa","NI":"North America","NL":"Europe","NO":"Europe","NP":"Asia","NR":"Australia","NU":"Australia","NZ":"Australia","OM":"Asia","PA":"North America","PE":"South America","PF":"Australia","PG":"Australia","PH":"Asia","PK":"Asia","PL":"Europe","PM":"North America","PN":"Australia","PR":"North America","PS":"Asia","PT":"Europe","PW":"Australia","PY":"South America","QA":"Asia","RE":"Africa","RO":"Europe","RS":"Europe","RU":"Europe","RW":"Africa","SA":"Asia","SB":"Australia","SC":"Africa","SD":"Africa","SE":"Europe","SG":"Asia","SH":"Africa","SI":"Europe","SJ":"Europe","SK":"Europe","SL":"Africa","SM":"Europe","SN":"Africa","SO":"Africa","SR":"South America","ST":"Africa","SV":"North America","SY":"Asia","SZ":"Africa","TC":"North America","TD":"Africa","TF":"Antarctica","TG":"Africa","TH":"Asia","TJ":"Asia","TK":"Australia","TM":"Asia","TN":"Africa","TO":"Australia","TR":"Asia","TT":"North America","TV":"Australia","TW":"Asia","TZ":"Africa","UA":"Europe","UG":"Africa","US":"North America","UY":"South America","UZ":"Asia","VC":"North America","VE":"South America","VG":"North America","VI":"North America","VN":"Asia","VU":"Australia","WF":"Australia","WS":"Australia","YE":"Asia","YT":"Africa","ZA":"Africa","ZM":"Africa","ZW":"Africa"};
if(google.loader.ClientLocation)
{
visitor_lat = google.loader.ClientLocation.latitude;
visitor_lon = google.loader.ClientLocation.longitude;
visitor_city = google.loader.ClientLocation.address.city;
visitor_region = google.loader.ClientLocation.address.region;
visitor_country = google.loader.ClientLocation.address.country;
visitor_countrycode = google.loader.ClientLocation.address.country_code;
if(visitor_countrycode!= null)
{
var Cont = Continent[visitor_countrycode];
//alert(Cont);
}
//
document.getElementById('yourinfo').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon + '</p><p>Location: ' + visitor_city + ', ' + visitor_region +', Continent : ' + Cont + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
}
else
{
document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';
}
</script>
</body>
Redirect website to Hong Kong and Spain based on their ip-address?
Method 1
You can use geoIP for apache to redirect. The same has been answered here as well.
Method 2
Many times in shared hostings, you can not install additional modules. In those cases you can use a third party api service, like http://www.geoplugin.net/.
Here's a function to use get Country details:
function getLocationInfoByIp(){
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = @$_SERVER['REMOTE_ADDR'];
$result = array('country'=>'', 'city'=>'');
if(filter_var($client, FILTER_VALIDATE_IP)){
$ip = $client;
}elseif(filter_var($forward, FILTER_VALIDATE_IP)){
$ip = $forward;
}else{
$ip = $remote;
}
$ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));
if($ip_data && $ip_data->geoplugin_countryName != null){
$result['country'] = $ip_data->geoplugin_countryCode;
$result['city'] = $ip_data->geoplugin_city;
}
return $result;
}
Ref.
You can use the above function to redirect users:
$visitor = getLocationInfoByIp();
if($visitor["country"]=="HK"){
//Redirect to Hong Kong Site.
}
elseif($visitor["country"]=="ES"){
//Redirect to Hong Kong Site.
}
Method 3
You can use Hostip APIs. More here.
http://api.hostip.info/country.php
US
http://api.hostip.info/get_html.php?ip=12.215.42.19
Country: UNITED STATES (US)
City: Sugar Grove, IL
IP: 12.215.42.19
http://api.hostip.info/get_html.php?ip=12.215.42.19&position=true
Country: UNITED STATES (US)
City: Sugar Grove, IL
Latitude: 41.7696
Longitude: -88.4588
IP: 12.215.42.19
http://api.hostip.info/get_json.php
{"country_name":"UNITED STATES","country_code":"US","city":"Sugar Grove, IL","ip":"12.215.42.19"}
http://api.hostip.info/?ip=12.215.42.19
[use the URL above for an example - XML too long to paste below]
Related Topics
Decode Gzipped Web Page Retrieved Via Curl in PHP
Session Data Lost in Chrome Only
Why Doesn't MySQL Support Millisecond/Microsecond Precision
Why Is This PHP Call to Json_Encode Silently Failing - Inability to Handle Single Quotes
Prevent Sent Emails Treated as Junk Mails Using PHP Mail Function
Adding Months to a Date in JavaScript
How to Strip a Tag and All of Its Inner HTML Using the Tag'S Id
PHP Get All the Images from Url Which Width and Height ≫=200 More Quicker
How to Use a String as an Array Index Path to Retrieve a Value
How to Split a String by Multiple Delimiters in PHP
If Statement in the Middle of Concatenation
Call to Undefined Function Curl_Init().
Sha1 VS Md5 VS Sha256: Which to Use For a PHP Login
Laravel - Eloquent or Fluent Random Row
Adding Minutes to Date Time in PHP
Difference Between Method Calls $Model-≫Relation(); and $Model-≫Relation;