The title of our posts is “How To Get Country of Visitor in PHP” however our actual mission here is to get to know the country of our visitor and redirect him to another page/domain or url in php.
The simplest way to do it in php is as follow:
- Download the following class or file in layman’s term from the below url
http://www.geoplugin.com/_media/webservices/geoplugin.class.phps
2. Upload it on your server and then create a new file in the same directory. Lets name the new file index.php.
3. Paste the following code in the index.php
<?php
require_once('geoplugin.class.php');
$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 == "PK") {
header('Location: https://hostmayo.com/pk/');
}
else if ($var_country_code == "US") {
header('Location: https://hostmayo.com/');
}
else {
header('Location: http://en.wikipedia.org/');
}
?>
4. Just change the locations starting with https to what ever place you want to redirect the user to.
5. The list of country codes used in the above scripts can be found in the list here
http://www.geoplugin.com/iso3166
6. We also have enclosed the both files with this post. However the test.php in enclosed package just tells you the country code. It is just to see if your script is working fine.
EXTRA TIP:
You could do this without require_once(‘geoplugin.class.php’); like so:
<?php
$a = unserialize(file_get_contents(‘http://www.geoplugin.net/php.gp?ip=’.$_SERVER[‘REMOTE_ADDR’]));
$countrycode= $a[‘geoplugin_countryCode’];
if ($countrycode==’US’)
header( ‘Location: http://example1.com’ ) ;
else
header( ‘Location: http://example2.com’ ) ;
?>