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:

 
< ?php
 
function dlang($Var)
{
 if(empty($GLOBALS[$Var]))
 {
  $GLOBALS[$Var]=(!empty($GLOBALS['_SERVER'][$Var]))?
  $GLOBALS['_SERVER'][$Var]:
  (!empty($GLOBALS['HTTP_SERVER_VARS'][$Var]))?
  $GLOBALS['HTTP_SERVER_VARS'][$Var]:'';
 }
}
 
function language()
{
 // Detect HTTP_ACCEPT_LANGUAGE & HTTP_USER_AGENT.
 dlang('HTTP_ACCEPT_LANGUAGE');
 dlang('HTTP_USER_AGENT');
 
 $_AL=strtolower($GLOBALS['HTTP_ACCEPT_LANGUAGE']);
 $_UA=strtolower($GLOBALS['HTTP_USER_AGENT']);
 
 // Try to detect Primary language if several languages are accepted.
 foreach($GLOBALS['_LANG'] as $K)
 {
  if(strpos($_AL, $K)===0)
   return $K;
 }
 
 // Try to detect any language if not yet detected.
 foreach($GLOBALS['_LANG'] as $K)
 {
  if(strpos($_AL, $K)!==false)
   return $K;
 }
 foreach($GLOBALS['_LANG'] as $K)
 {
  if(preg_match("/[\[\( ]{$K}[;,_\-\)]/",$_UA))
   return $K;
 }
 
 // Return default language if language is not yet detected.
 return $GLOBALS['_DLANG'];
}
 
// Define default language.
$GLOBALS['_DLANG']='es';
 
// Define all available languages.
// WARNING: uncomment all available languages
 
$GLOBALS['_LANG'] = array(
'es',
'en'
);
?>
 

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:

 
< ?php
session_start();
include('lang.php'); //The language detection function
echo language(); //Display the language
?>
 

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:

 
< ?php
//proc all page display
include('lang.php'); //language detector
 
class Session
{
	var $lang;     	   //Username given on sign-up
	var $url;          //The page url current being viewed
        var $referrer;     //Last recorded site page viewed
 
	/* Class constructor */
   function Session(){
      $this->time = time();
      $this->startSession();
   }
 
   function cf($filename){//function to clean a filename string so it is a valid filename
   		$fp = explode('/',$filename);
		$num = count($fp);
		return $fp[$num-1];
	}
 
   /**
    * startSession - Performs all the actions necessary to
    * initialize this session object. Tries to determine if the
    * the user has logged in already, and sets the variables
    * accordingly. Also takes advantage of this page load to
    * update the active visitors tables.
    */
   function startSession(){
   		session_start();   //Tell PHP to start the session
 
		/* Set referrer page */
      if(isset($_SESSION['url'])){
         $this->referrer = $search = $this->cf($_SESSION['url']);
      }else{
         $this->referrer = "/";
      }
 
      /* Set current url */
      $this->url = $_SESSION['url'] = $this->cf($_SERVER['PHP_SELF']);
 
	  /* Set user-determined language: */
	  	//set up languages array:
		  $langs = array('en','es');
		//
	  if(isset($_GET['lang'])){
	  	if(in_array($_GET['lang'],$langs)){
			$this->lang =  $_SESSION['lang'] = $_GET['lang'];
		}
	  }
	  if(!isset($_SESSION['lang']) || !in_array($_SESSION['lang'],$langs)){
	  	  $this->lang = $_SESSION['lang'] = language();
	  }
	}
};
/**
 * Initialize session object - This must be initialized before
 * the form object because the form uses session variables,
 * which cannot be accessed unless the session has started.
 */
$session = new Session;
 
?>
 

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

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

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

 
<a href="?lang=es">Change to Spanish</a>
 

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)

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 (1317 downloads)

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