Get Country By IP Address in PHP

This simple function allows you to detect a country code and city of your site visitors, using the www.geoplugin.net service. You may use this data to add default values in registration form or use it for any other purposes, like blocking access to your site from special regions.

[View All Snippets]
Show Plain Text »
  1. <?php
  2. function getLocationInfoByIp(){
  3.     $client  = @$_SERVER['HTTP_CLIENT_IP'];
  4.     $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
  5.     $remote  = @$_SERVER['REMOTE_ADDR'];
  6.     $result  = array('country'=>'', 'city'=>'');
  7.     if(filter_var($client, FILTER_VALIDATE_IP)){
  8.         $ip = $client;
  9.     }elseif(filter_var($forward, FILTER_VALIDATE_IP)){
  10.         $ip = $forward;
  11.     }else{
  12.         $ip = $remote;
  13.     }
  14.     $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));    
  15.     if($ip_data && $ip_data->geoplugin_countryName != null){
  16.         $result['country'] = $ip_data->geoplugin_countryCode;
  17.         $result['city'] = $ip_data->geoplugin_city;
  18.     }
  19.     return $result;
  20. }
  21. ?>


Test Result:
Country code: ID
City:
Create Your Free Account
Please remember that this information is essential to use our services correctly.
After creating the account you will be able to download all of our FREE products.
Fields marked with * are mandatory






Please send me information about updates, new products, specials and discounts from ApPHP!
We recommend that your password should be at least 6 characters long and should be different from your username/email. Please use only letters of the English alphabet to enter your name.

Your e-mail address must be valid. We use e-mail for communication purposes (order notifications, etc). Therefore, it is essential to provide a valid e-mail address to be able to use our services correctly.

All your private data is confidential. We will never sell, exchange or market it in any way. Please refer to Privacy Policy.

By clicking "Create Account", you are indicating that you have read and agree to the ApPHP Terms & Conditions.