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 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($ip_address = ''){
  3.     if (empty($ip_address)) {
  4.         $client  = @$_SERVER['HTTP_CLIENT_IP'];
  5.         $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
  6.         $server  = @$_SERVER['SERVER_ADDR'];
  7.         $remote  = @$_SERVER['REMOTE_ADDR'];
  8.         if(!empty($client) && filter_var($client, FILTER_VALIDATE_IP)){
  9.             $ip = $client;
  10.         }elseif(!empty($forward) && filter_var($forward, FILTER_VALIDATE_IP)){
  11.             $ip = $forward;
  12.         }elseif(!empty($server) && filter_var($server, FILTER_VALIDATE_IP)){
  13.             $ip = $server;
  14.         }else{
  15.             $ip = $remote;
  16.         }
  17.     } else {
  18.         $ip = $ip_address;
  19.     }
  21.     $ip_data = unserialize(file_get_contents("".$ip));
  22.     $result  = ['country'=>'', 'city'=>''];
  24.     if($ip_data && $ip_data['geoplugin_countryCode'] != null){
  25.         $result['country'] = $ip_data['geoplugin_countryCode'];
  26.         $result['city'] = $ip_data['geoplugin_city'];
  27.     }
  28.     return $result;
  29. }
  30. ?>

Test Result:
Country code:
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.

Quick Registration with: Facebook / Google