Multiple Languages on any Page Dynamically

Thursday, April 24th, 2008 4:49 pm by Kevin Martin Print this Article Print this page Comments Comment Share This Share This

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.php

function 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

End of Article. Copyright Devlounge.
  • Post Time April 24, 2008 at 5:58 pm (permalink)

    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.

  • Post Time April 25, 2008 at 8:39 am (permalink)

    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!

  • Post Time April 25, 2008 at 3:56 pm (permalink)

    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.

  • Note: If you are commenting here for the first time, your comment will be sent into a moderation queue before being published. Please use your email address in order to identify yourself for your future comments. Clean XHTML: Use standards ready code tags in your comments. For example, cite a comment or phrase from an article with < blockquote > tags.

    About this author

    Login See more posts by Kevin Martin, or visit Kevin Martin's homepage.

    Subscribe

    SubscribeFirst time here, or frequent flyer. Whatever the case may be, we highly recommend subscribing to our feeds so you can get the latest updates without visiting the site. It's just a thought - don't say we didn't tell you so.

    Sponsors

    PSD to HTML, PSD to XHTML Service by PSD2HTML.com. You Design - We XHTML / CSS.

    Related Content

    Close
    E-mail It