Get Country By IP Address in PHP


/ Published in: PHP
Save to your folder(s)

This simple function allows you to getect 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.


Copy this code and paste it in your HTML
  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
  15. (file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));
  16. if($ip_data && $ip_data->geoplugin_countryName != null){
  17. $result['country'] = $ip_data->geoplugin_countryCode;
  18. $result['city'] = $ip_data->geoplugin_city;
  19. }
  20. return $result;
  21. }
  22. ?>

URL: http://www.apphp.com/index.php?snippet=php-get-country-by-ip

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.