Search code examples
phplang

How to make multiple language website with including appropriate files on PHP?


I have 2 languages in my website. I want to include appropriate file according to selected language. For example, <a href='index.php?lang=en'>English</a> and <a href='index.php?lang=tr'>Turkish</a>. If user clicks over first hyperlink (English) I want to display this information (with HTML tags):

<h1>Hello</h1>
How are you

Otherwise:

<h1>Selam</h1>
Nasılsın

I also dont want user selected language to change if user go to other page inside website.

How can I do that?


Solution

  • You could use .ini files to hold the translated versions of you text for example, en.ini will contain:

    hello    = "Hello"
    greeting = "How are you"
    

    While tr.ini will contain:

    hello    = "Selam"
    greeting = "Nasılsın"
    

    Both are simple text files (saved in UTF-8 format). Now you can see that the strings have common names in all languages (hello & greeting) which cab be used in the code like this:

    // First, load the appropriate language file:
    
    $lang = "en";
    $strings = parse_ini_file( "$lang.ini" );
    
    // Now we can use the following code no matter what $lang indicates (tr or en):
    
    echo( "<h1>{$strings[ "hello" ]}</h1><br/>{$strings[ "greeting" ]}" );
    

    One thing you should be concious of:

    • Since parse_ini_file reads a file from the file system, you must validate the value in $lang very carefully! don't rely on user input in any way for the value of $lang as it might be malicious (link to page.php?lang=en is not good enough). Check the value of $lang against your own white list for example: $langs = array( "en", "tr" ); and if that fails, redirect to a general error page or something...