Change Language Automatically According to the Visitor Country

This simple code demonstrates how to change automatically site language, according to the visitor's country. If you implement this script in your site it will open the page in the language of your visitor.

[View All Snippets]
Show Plain Text »
  1. <?php
  2.  
  3. // prepare reload to local version according by first visit        
  4. session_start();            
  5. $location_reload = isset($_SESSION["loc_reload"]) ? (bool)$_SESSION["loc_reload"] : false;
  6. // prepare reload to local version according by first visit
  7. if(!$location_reload){
  8.     $location = visitor_location();
  9.     if(in_array($location["country"], array("RU", "BY", "UA"))){
  10.         $_SESSION["loc_reload"] = true;
  11.         header("location: ru/index.php");
  12.         exit;
  13.     }else if(in_array($location["country"], array("IL"))){
  14.         $_SESSION["loc_reload"] = true;
  15.         header("location: he/index.php");
  16.         exit;
  17.     }        
  18. }
  19.  
  20. function visitor_location(){
  21.     $client  = @$_SERVER["HTTP_CLIENT_IP"];
  22.     $forward = @$_SERVER["HTTP_X_FORWARDED_FOR"];
  23.     $remote  = @$_SERVER["REMOTE_ADDR"];
  24.     $result  = array("country"=>"", "city"=>"");
  25.     if(filter_var($client, FILTER_VALIDATE_IP)){
  26.         $ip = $client;
  27.     }elseif(filter_var($forward, FILTER_VALIDATE_IP)){
  28.         $ip = $forward;
  29.     }else{
  30.         $ip = $remote;
  31.     }
  32.     $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));
  33.     if($ip_data && $ip_data->geoplugin_countryName != null){
  34.         $result["country"] = $ip_data->geoplugin_countryCode;
  35.         $result["city"] = $ip_data->geoplugin_city;
  36.     }
  37.     return $result;
  38. }
  39. ?>
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.