Multi Language Support to Website using PHP

We will create multi language supported page. here i will use Spanish Language with English. you can set another else.

Create a separate PHP file for languages e.g. lang_en.php, lang_sp.php, etc. and define constants variable in it.

Include the file according to language selection and use the constant variables in the place of string text on the web page.

Ex. : here we will create 2 php files [1]. lang_en.php (it store English data)  and [2]. lang_sp.php (it store Spanish data).


define("_REGISTER", "Register");
define("_NAME", "Name");
define("_USERNAME", "Username");
define("_EMAIL", "Email");
define("_ADDRESS", "Address");
define("_SUBMIT", "Submit");


define("_REGISTER", "Registro");
define("_NAME", "Nombre");
define("_USERNAME", "Nombre de usuario");
define("_EMAIL", "Email");
define("_ADDRESS", "Dirección"); 
define("_SUBMIT", "Enviar");

Add <meta > tag to set charset to utf8.

Create a <select > element with language options and create a <form> where use constant variables. Submit the language form when the option is selected from the <select> element.

Initialize $_SESSION['lang'] with submitted language value and include a file.



// Set Language variable
if(isset($_GET['lang']) && !empty($_GET['lang'])){
 $_SESSION['lang'] = $_GET['lang'];

 if(isset($_SESSION['lang']) && $_SESSION['lang'] != $_GET['lang']){
  echo "<script type='text/javascript'> location.reload(); </script>";

// Include Language file
 include "lang_".$_SESSION['lang'].".php";
 include "lang_en.php";

<!doctype html>
 <meta content='text/html; charset=UTF-8' http-equiv='Content-Type'/>
 <body >
 function changeLang(){

 <!-- Language -->
 <form method='get' action='' id='form_lang' >
   Select Language : <select name='lang' onchange='changeLang();' >
   <option value='en' <?php if(isset($_SESSION['lang']) && $_SESSION['lang'] == 'en'){ echo "selected"; } ?> >English</option>
   <option value='pl' <?php if(isset($_SESSION['lang']) && $_SESSION['lang'] == 'pl'){ echo "selected"; } ?> >Spanish</option>

<!-- Form -->
 <h1><?= _REGISTER ?></h1>
 <form method='post' action=''>
  <?= _NAME ?> : <input type='text' name='name' /><br>
  <?= _USERNAME ?> : <input type='text' name='username' /><br>
  <?= _EMAIL ?> : <input type='text' name='email' /><br>
  <?= _ADDRESS ?> : <input type='text' name='address' /><br>
  <input type='submit' value='<?= _SUBMIT ?>'>

Leave a Reply

Your email address will not be published. Required fields are marked *