The Urbano A. Company’s Blog
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:
< ?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 (544 downloads)
For suggestions, feedback, hates... please comment
| Print article | This entry was posted by alex on April 1, 2008 at 3:51 pm, and is filed under General talk, PHP, Programming, Web-related. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
No comments yet.
No trackbacks yet.
New threat for all Joomla and WordPress installations
about 5 months ago - 2 comments
There is a new BOT out there, and one of the bad ones. I have started receiving traffic from it in my servers over the past week, and after some investigation it turns out it is quite a powerful bot, and so simple to use even a kid with a computer could use it.
The bot More >
Parse links in user comments
about 5 months ago - No comments
When you allow users to comment and post stuff to your website, it is interesting and useful allowing them to post links and other stuff. But how can we do so easily?
Surely there is BBCode, phpBB, allowing only some HTML tags… etc but how easy is this approach for the end user? Of course some More >
Calculate age in PHP from timestamp
about 6 months ago - No comments
If you ever wanted to calculate someone’s age in PHP from a birth timestamp, you must take into account that the age is more than the number of years, since days and months are also important, so I wrote a simple function that will return the exact age for a given timestamp:
function getAge($birth){
$t = time();
$age More >
Easiest PHP file upload
about 7 months ago - No comments
Hello people,
I want to share with all of you a file upload class I have developed, that makes it stupid simple to upload files haha
The PHP class:
First of all, here is the PHP class you will need:
< ?php
//Uploader class, by Alex
// This class is meant to handle all kinds of file uploads for DJs Music
// More >
Easily assign an image to a post in WordPress
about 1 year ago - 1 comment
Have you ever wondered how to assign an image to a certain post using WordPress? Surely there are some plugins that try to do this, and maybe they accomplish it, but probably slowing down your blog.
Well, here is a way of doing it without slowing the blog or installing any sort of additional plugins. When More >
Did you mean… ? In php
about 1 year ago - 13 comments
In a new website I am developing for a client I had to add the usual “Did you mean… ?” in the search results for her. Si I started thinking for the easiest way to do this.
There are actually a lot of php functions out there to look for similar text. The most obvious one?
similar_text()
You More >
How we became web developers…
about 1 year ago - 3 comments
I normally write to those web developers/programmers who are already good, experienced, and thus the articles are somewhat advanced.
But today I got up feeling nostalgic I guess, or I just felt like remembering back on my www birth, on my first impression of the Internet, my first site online, my first steps in w3c standards, More >
Using Gravatars in your blog comments
about 1 year ago - No comments
I’m sure you have seen in some blogs or websites that as soon as you enter your email, or other people do, an avatar is displayed for them. If you haven’t still set your own you should do that now.
A Gravatar is a “Globally Recognized Avatar”, meaning that anyone can display yours if they know More >
PHP easy image editing:
about 1 year ago - 3 comments
Do you have a picture upload and you don’t know how to easily resize/edit the uploaded images?
Well here is a solution for php that will make your life really easy!
It is called Asido, so you may go and download their code, to follow this tutorial.
First of all I’ll suppose you already know how to upload More >
Writing a simple Facebook App
about 1 year ago - 1 comment
In this tutorial I am going to show you how to create a simple Facebook application.
Getting the basics
First of all you’ll need to install the developer application on Facebook. To do this log in to your Facebook account and visit this link here to install the Developer application. You should be redirected to this screen:
* More >