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?
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.
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");
} ?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With