Scripting

EN NL TR

The previous article

Home

The next article

How to talk to the user in the correct language if your site is in multiple languages

What is the goal?

The PHP script presented here will detect the prefered user language.  Once you know the language, you, the scripter, can now make the content differ.  The final action is yours to decide, you can include the correct language file or you can use a META-TAG to redirect the user to the correct localized page.  The script does assume that you define a list with the supported languages.

Should you need it, this script will also detect the country code (if set).
 

How to use it...

You include the script in your program and the script will automaticly detect the user language & country.

# Setup our supported languages... (the languages in the $knownlangs-array are accepted as valid)
$knownlangs = array("nl", "en", "tr"); # if you specify NULL then the script will set the array to the languages it knows off
$deflang = "en";  # if you wish, you can also write $deflang = "en-us"; or $default = "en-uk"; etc.

# Detect the language
include("languagedetection.php");

# After the script execution, the following variables are avaible
echo "$lclist ";     # $lclist : the full list with the languages accepted by the client's browser
echo "$lctag ";     # $lctag : the tag we are supporting (includes the country code if any)
echo "$quality ";  # $quality : the quality as defined by the browesr
echo "$lang ";      # $lang : the language code
echo "$country "; # $country : the country code (if any)
 

The code...

The PHP code is pretty well documented so you should have no problems with understanding it if you know PHP.  The basic trick is to parse the HTTP_ACCEPT_LANGUAGE variable which the browser will include in the GET/POST-request.  We actually search for the supported language with the highest quality/priority.

Some language codes also include a country code (for example en-us and en-uk (respectivily United States and United Kingdom).  If the information is avaible, then the script will extract it and return to you via a variable.
 

The script view the source code  
An example script view the source code test the script on this server
Another example script view the source code test the script on this server

 

When it does not work...

... then there's probably a reason for it.  If you cannot figure it out, please contact me at fibergeek @ codegurus.be.  IMPORTANT : The script relies on the preg_match function which isn't available on older PHP versions, check your PHP manual!

 

Version information

Detailed information about the changes are available inside the script source code.

2003-12-18 - Version 1
2004-01-07 - Version 2
 

External links

How To Make Your Web Site Respond To Browser Language Requests
2-letter Language Codes (ISO 639)

 

The previous article

Home

The next article