Multilingual website in PHP

Posted by Sandeep | Posted in PHP | Posted on 18-11-2012

1

Multilingual website means that supports multiple languages i.e If your website is accessed in USA, it will be in English, if it is accessed in India, it will be in Hindi, If it is accessed in France, it will be in French and so on.

In PHP we can easily develop a multilingual website. The concept behind this is very simple. We can use Cookie based approach to develop such a website.

Here are the steps to develop a multilingual website:-

  1. Get the location of the user using Maxmind database.
  2. Get the country code from the location.
  3. You can easily get country vs language database from internet.
  4. Now against the location, you can get the language code.
  5. Now set the cookie of the user with language code.
  6. Keep a common directory as lang in your root folder and have separate property files for each language for example for English keep one en.php, for Hindi keep hi.php and so on.
  7. Now include this language file on the run time so that your website content appears as per location of the user.

Here is the sample code to achieve this:-

The lang directry:-

lang/en.php code:-

<?php

$lang=array();

$lang[‘ERR_USERNAME_REQ’]=”Please enter Username”;

$lang[‘ERR_PASSWORD_REQ’]=”Please enter Password”;

$lang[‘ERR_EMAIL_REQ’]=”You have to enter your e-mail address”;

$lang[‘ERR_GENDER_REQ’]=”You have to select your gender”;

$lang[‘ERR_USERNAME_EXISTS’]=”Username is already in use”;

$lang[‘ERR_INVALID_EMAIL’]=”Email address id not valid”;

$lang[‘LABEL_USERNAME’]=”Username “;

?>

 

Determining the location of the user and setting the language cookie:-

location.php file:-

<?php

include(“geoipcity.inc”);

include(“geoipregionvars.php”);

$giCity = geoip_open(“GeoLiteCity.dat”,GEOIP_STANDARD);

$ip = $_SERVER[‘REMOTE_ADDR’];

$result = geoip_record_by_addr($giCity, $ip);

$country_code = $result->country_code;

if($country_code==’IN’)

{

setcookie(“lang”,”hi”,time()+(60*60*24*30));

}

else

{

setcookie(“lang”,”en”,time()+(60*60*24*30));

}

geoip_close($giCity);

header(“Location:index.php”);

exit;

?>

Including the language file:-

header.php file

<?php

if(!isset($_COOKIE[‘lang’]) || $_COOKIE[‘lang’]==””)

{

include(“location.php”);

}

$lang_file=$_COOKIE[‘lang’].”.php”;

include(“lang/$lang_file”);

?>

 

Now following all these steps we can easily develop a multilingual website. Please keep in mind all the content,  labels, error messages of your website need to be in the language specific file and your php should have the array variables instead of direct labels. For example instead of having

<label>Username<label>, you should use <label><?php echo $lang[LABEL_USERNAME’];?></label>

Thus all the content will be replaced when you include language specific files and your website will support multilingual feature.

Cheers!