Change Language Automatically According to the Visitor Country


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

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.


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

URL: http://www.apphp.com/index.php?snippet=php-change-language-according-to-visitor-country

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.