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

lang_en.php

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

lang_sp.php

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

index.php

<?php
session_start();

// 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
if(isset($_SESSION['lang'])){
 include "lang_".$_SESSION['lang'].".php";
}else{
 include "lang_en.php";
}
?>

<!doctype html>
<html>
 <meta content='text/html; charset=UTF-8' http-equiv='Content-Type'/>
 <body >
 <script>
 function changeLang(){
  document.getElementById('form_lang').submit();
 }
 </script>

 <!-- 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>
  </select>
 </form>

<!-- 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 ?>'>
 </form>
 </body>
</html>

Leave a Reply

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