How To Get Country of Visitor in PHP

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:

  1. Download the following class or file in layman’s term from the below url

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

$geoplugin = new geoPlugin();
// create a variable for the country code
$var_country_code = $geoplugin->countryCode;
// redirect based on country code:
if ($var_country_code == "PK") {
else if ($var_country_code == "US") {
else {
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

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.


You could do this without require_once(‘geoplugin.class.php’); like so:

$a = unserialize(file_get_contents(‘’.$_SERVER[‘REMOTE_ADDR’]));
$countrycode= $a[‘geoplugin_countryCode’];
if ($countrycode==’US’)
header( ‘Location:’ ) ;
header( ‘Location:’ ) ;


Download countryscript

Leave a Reply

Notify of