Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change language of site with a html button

In PHP, I want to change the language (English, German, etc) of the site when clicking a button. Is this the right way to approach that problem?

<?php 
  $language;
  if ($language == "en") {
    include("headerEn.php");
  } else {
    include("header.php");
  } 
?>
<a href="index.php"><?php $language = "en"; ?>
<img src="images/language/languageNO.png"></a>

<a href="index.php"><?php $language = "no"; ?>
<img src="images/language/languageEN.png"></a>

What is the best way to change the language of the site and have it persist when the user returns?

like image 607
kensil Avatar asked Feb 25 '13 13:02

kensil


People also ask

How do you change the language of a website in HTML?

In a nutshell Always add a lang attribute to the html tag to set the default language of your page. If this is XHTML 1. x or an HTML5 polyglot document served as XML, you should also use the xml:lang attribute (with the same value). If your page is only served as XML, just use the xml:lang attribute.


2 Answers

you can do this by

<a href="index.php?language=en">
<a href="index.php?language=no">

and get the languages and store them in cookie and include file according to cookie like

if ( !empty($_GET['language']) ) {
    $_COOKIE['language'] = $_GET['language'] === 'en' ? 'en' : 'nl';
} else {
    $_COOKIE['language'] = 'nl';
}
setcookie('language', $_COOKIE['language']);

and than

if ( $_COOKIE['language'] == "en") {
   include("headerEn.php");
} else {
   include("header.php");
} ?>
like image 102
NullPoiиteя Avatar answered Oct 13 '22 12:10

NullPoiиteя


To give a solution without changing your approach, You can do like this.

<?php 
if(isset($_GET['language']))
  $language = $_GET['language'];
else
  $language = "";

if ($language == "en") {
   include("headerEn.php");
} else {
   include("header.php");
} ?>

<a href="index.php?language = en"><img src="images/language/languageNO.png">      </a>
<a href="index.php?language = no"><img src="images/language/languageEN.png"></a>

If you want to keep the selection, you can store this value in Database or Session.

like image 32
Edwin Alex Avatar answered Oct 13 '22 11:10

Edwin Alex