Feature
Post

Category
Code


Multiple Languages on any Page Dynamically

Have you ever thought of adding multiple languages to your website or have done so using methods such as creating separate directories for a completely new website with only that one language? The PHP language can make this easy for your site.

To begin, you will need atleast 4 files: index.php, index.html, lang.php, lang_english.php, and any other language file you want in the format of lang_[language].php.

This will work by creating variables within your html files. Such variable would look like {VARIABLE}. We would then replace them with the variables in the language files. An example of how a user would use this would be: Bob goes to your website and the default language is English. He then wants to change the language to Spanish, so he will click on a link in the menu bar. The page refreshes with the new language selection visible.

First we create an html file (index.html) in the default language:

<html>

    <head>

        <title>Language Test</title>

    </head>

    <body>

        <p>Hello World</p>

    </body>

</html>

Then we convert the text into variables and add the links to the different languages:

<html>

    <head>

        <title>{TITLE}</title>

    </head>

    <body>

        <div id=”menu”>

            <a href=”index.php?lang=english”>English</a>

            <a href=”index.php?lang=spanish”>Spanish</a>

        </div>

        <p>{INTRO}</p>

    </body>

</html>

Simple enough, right? Now for a language file. To make things easier, we will use an associative array of strings:

<?php

// lang_english.php

$lang = array(

    'TITLE' => 'Language Test',

    'INTRO' => 'Hello World',

);

?>
<?php

// lang_spanish.php

$lang = array(

    'TITLE' => 'Prueba de Lenguage',

    'INTRO' => 'Hola, Mundo',

);

?>

A note I have to make about variable naming: The variables do not have to be in all uppercase, though it is common practice. You have the freedom to name them anything you want and however way you want to.

The language converter will also act like a pseudo-template engine in which it loads the html, converts some data, then displays it. This is why we created the index.html file above. Now, to load, we can simply use file_get_contents to access the data within the html. We would also have to include a language file based on the user input and then convert using another function called strtr.

<?php

// lang.phpfunction get_lang($file)

{

    // The default lang

    $user_lang = 'english';

// Lets see if the user clicked on a language

    if (isset($_GET['lang']) && !empty($_GET['lang']))

    {

        $user_lang = $_GET['lang'];

    }

// Include a language file

    include 'lang_' . basename($user_lang) . '.php';

// Get the data from the HTML

    $html = file_get_contents($file);

// Create an empty array for the language variables

    $vars = array();

// Scroll through each variable

    foreach($lang as $key => $value)

    {

        // Turn 'THIS' to '{THIS}'

        $vars['{' . $key . '}'] = $value;

    }

// Finally convert the strings

    $html = strtr($html, $vars);

// Return the data

    return $html;

}

?>

The comments within the function should be enough. Now going on, we need to use this within index.php:

<?php

// index.php// Get the function

include 'lang.php';

// Convert and display

get_lang('index.html');

?>

This pretty much sums it up on how to create a page with multiple languages. All you need to do is add language files (lang_[language_name].php). You may also order the structure of your site by keeping the language files in its own folder like /languages/ and put the html files into a directory like /html/. You must also adjust the paths in the function and everywhere else to suit a new structure you put in. Also, so that the user wont have to click on the Spanish conversion link every time, you may also make it work via cookie, or via a database if the user has an account on your site.

Source Files


  1. By nemetral posted on April 24, 2008 at 5:58 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    In terms of URI architecture, there’s also a decision to be made between a) keeping the current language visible (like a subdomain or a virtual folder i.e. http://language.domainname.tld or http://domainname.tld/language/) or b) hiding it from the user in a session, both with pros and cons.

  2. By Wally posted on April 25, 2008 at 8:39 am
    Want an avatar? Get a gravatar! • You can link to this comment

    It may be beyond the scope of your article, but I would like to point out that you should never blindly include a file based on a variable being sent by the request. It makes your script vulnerable to something called Poison Null Byte File Retrieval. For example, I could make a request to your script like this: http://server.com/index.php?lang=/../etc/passwd%00.htm (or some variation of). If you’re familiar with Linux paths you’ll see the problem immediately, but basically the passwd file contains information about all the user accounts on the machine, obviously bad for security. In this case the entire contents of that file would be sent to my browser in plain text.

    I would recommend maintaining a list of the valid languages, that way you can test the requested language against your list before including the appropriate file. If the requested language isn’t in the list, it would be simple enough to load whatever default you chose.

    Language is an issue often overlooked by developers, so thanks for putting this out there, it’s definitely a start in the right direction!

  3. By Kevin Martin posted on April 25, 2008 at 3:56 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Well, if you look closer, you will see that the language path is prefixed and also has a suffix. And yes, ofcourse, you can also double check that you have the language in a database, or else show the default language.

    One thing that just struck me was that you may also be able to put basename() and this would also help against an attack like that. I don’t know why it didn’t strike me earlier.

    Thank you for you comments,
    Kevin Martin.

  4. By DNoe posted on May 18, 2008 at 2:47 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    I would suggest taking a look into the Google AJAX Language API for a more extensible solution. You can use a similar approach to what you do here with tags, but use JavaScript arrays for your tags and let Google translate it for you.

    Of course, I have no way of knowing how accurate a translation Google returns, but it sure seems better than hard coding text blocks of multiple languages.

  5. By Nibohs posted on June 3, 2009 at 7:27 am
    Want an avatar? Get a gravatar! • You can link to this comment

    Hai Friends

    I create a multilanguage management section for my php site. Me added different languages there (chinies,japanes,french..etc). I used the google language transilater to transilate all the english words to other languages. But some languages fonts does’nt support . How can I solve this problem??. Any body can help me??

  6. By Katja Hollaar posted on August 4, 2009 at 11:15 am
    Want an avatar? Get a gravatar! • You can link to this comment

    Hi and thanks for posting this. I’m trying to implement multiple language support for my site being a php-dummy. Neither your sample files nor my sample implementation work. {Variables} are shown as {Variables} and the link with “index.php?lang=en” doesn’t lead anywhere. Is there a mistake in syntax or am I missing some steps in your tut? It would really be great if you (or anybody) could help me out. I’d certainly appreciate it!
    Thanks again,
    Katja Hollaar, the Netherlands

  7. Trackback