Visitor’s language detection in php

Is your site translated into more than one language? In case it is, you will find this topic really interesting, since it will allow you to automatically adapt your site's language to the user's.
In case your site is not translated, you can always use this to know the visitor's language... I'm sure you'll be able to find a good use for that information ;)

The basics

The way this script will find the visitor's language is fairly simple. First it will "ask" the client (a.k.a the http request sender) for its user agent and for its language, if set.
For our script to work we will have set a list of our "available" languages. If you just want to detect it you could stop the script here and return the language. If you are detecting the language to use it for your website then continue reading:
Before the script checks if the language was on the list it would check if it was the default or primary language, then if not, it would look up in the available languages, and if not again, then it would return to the default language.

This is a very useful tool you can check out working on my main site: http://urbanoalvarez.es which is translated into both Spanish and English, and for you it will most probably be in English...

Now let's start looking at the code:

  1.  
  2. < ?php
  3.  
  4. function dlang($Var)
  5. {
  6. if(empty($GLOBALS[$Var]))
  7. {
  8. $GLOBALS[$Var]=(!empty($GLOBALS['_SERVER'][$Var]))?
  9. $GLOBALS['_SERVER'][$Var]:
  10. (!empty($GLOBALS['HTTP_SERVER_VARS'][$Var]))?
  11. $GLOBALS['HTTP_SERVER_VARS'][$Var]:'';
  12. }
  13. }
  14.  
  15. function language()
  16. {
  17. // Detect HTTP_ACCEPT_LANGUAGE & HTTP_USER_AGENT.
  18. dlang('HTTP_ACCEPT_LANGUAGE');
  19. dlang('HTTP_USER_AGENT');
  20.  
  21. $_AL=strtolower($GLOBALS['HTTP_ACCEPT_LANGUAGE']);
  22. $_UA=strtolower($GLOBALS['HTTP_USER_AGENT']);
  23.  
  24. // Try to detect Primary language if several languages are accepted.
  25. foreach($GLOBALS['_LANG'] as $K)
  26. {
  27. if(strpos($_AL, $K)===0)
  28. return $K;
  29. }
  30.  
  31. // Try to detect any language if not yet detected.
  32. foreach($GLOBALS['_LANG'] as $K)
  33. {
  34. if(strpos($_AL, $K)!==false)
  35. return $K;
  36. }
  37. foreach($GLOBALS['_LANG'] as $K)
  38. {
  39. if(preg_match("/[\[\( ]{$K}[;,_\-\)]/",$_UA))
  40. return $K;
  41. }
  42.  
  43. // Return default language if language is not yet detected.
  44. return $GLOBALS['_DLANG'];
  45. }
  46.  
  47. // Define default language.
  48. $GLOBALS['_DLANG']='es';
  49.  
  50. // Define all available languages.
  51. // WARNING: uncomment all available languages
  52.  
  53. $GLOBALS['_LANG'] = array(
  54. 'es',
  55. 'en'
  56. );
  57. ?>
  58.  

Most of the important things in the above function are "self explanatory". If you have any problems understanding it, just ask!

Using it is very very simple, here is a simple script to see it working:

  1.  
  2. < ?php
  3. include('lang.php'); //The language detection function
  4. echo language(); //Display the language
  5. ?>
  6.  

As you can see using it is very simple, but it is still not perfect, because we still cannot change the language or store it, so we need another file, a session handler that will take care of storing and changing the language if neccesary.

File session.php:

  1.  
  2. < ?php
  3. //proc all page display
  4. include('lang.php'); //language detector
  5.  
  6. class Session
  7. {
  8. var $lang; //Username given on sign-up
  9. var $url; //The page url current being viewed
  10. var $referrer; //Last recorded site page viewed
  11.  
  12. /* Class constructor */
  13. function Session(){
  14. $this->time = time();
  15. $this->startSession();
  16. }
  17.  
  18. function cf($filename){//function to clean a filename string so it is a valid filename
  19. $fp = explode('/',$filename);
  20. $num = count($fp);
  21. return $fp[$num-1];
  22. }
  23.  
  24. /**
  25.   * startSession - Performs all the actions necessary to
  26.   * initialize this session object. Tries to determine if the
  27.   * the user has logged in already, and sets the variables
  28.   * accordingly. Also takes advantage of this page load to
  29.   * update the active visitors tables.
  30.   */
  31. function startSession(){
  32. session_start(); //Tell PHP to start the session
  33.  
  34. /* Set referrer page */
  35. if(isset($_SESSION['url'])){
  36. $this->referrer = $search = $this->cf($_SESSION['url']);
  37. }else{
  38. $this->referrer = "/";
  39. }
  40.  
  41. /* Set current url */
  42. $this->url = $_SESSION['url'] = $this->cf($_SERVER['PHP_SELF']);
  43.  
  44. /* Set user-determined language: */
  45. //set up languages array:
  46. $langs = array('en','es');
  47. //
  48. if(isset($_GET['lang'])){
  49. if(in_array($_GET['lang'],$langs)){
  50. $this->lang = $_SESSION['lang'] = $_GET['lang'];
  51. }
  52. }
  53. if(!isset($_SESSION['lang']) || !in_array($_SESSION['lang'],$langs)){
  54. $this->lang = $_SESSION['lang'] = language();
  55. }
  56. }
  57. };
  58. /**
  59.  * Initialize session object - This must be initialized before
  60.  * the form object because the form uses session variables,
  61.  * which cannot be accessed unless the session has started.
  62.  */
  63. $session = new Session;
  64.  
  65. ?>
  66.  

And the way we would use this hole script now would be:

  1.  
  2. include('session.php'); //This does all the session work for us:
  3. echo $_SESSION['lang']; //Display the language
  4.  

And to change it, place the following link anywhere in your site, without worrying for the location of the file!

  1.  
  2. <a href="?lang=es">Change to Spanish</a>
  3.  

And now change "es" for any language code you have inside your $langs array (in this example: $langs = array('en','es');)
If you need help with the language codes visit this post, or download the demo zip and open otherLangs.php (With a text editor)

[ad#blog]

See it working

To see how this works, just go to my main page (http://urbanoalvarez.es) and change the language around (Top right corner)

Or visit the custom demo page, with all options in the same place (Not many actually, but enough ;) )

Download demo

Download zip file - 30Kb (1625 downloads)

For suggestions, feedback, hates... please comment :)

About Alex

Hello! I'm Alejandro U. Alvarez, an engineering student at Universidad de Oviedo (Spain). I started programming during my Freshman year in Brookline High School (Boston, MA), and then got more and more interested in web development. I'm almost in love with JavaScript, although I keep an open mind with other languages

4 thoughts on “Visitor’s language detection in php

Leave a Reply