Change site language using html button

In PHP, I want to change the language (English, German, etc.) on the site at the click of a button. Is this the right approach to this 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 save it when the user returns?

+4
source share
6 answers

you can do it with

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

and get the languages ​​and save them in a cookie and include the file according to the cookie, for example

 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"); } ?> 
+6
source

It is always useful to have a default value, so you never end up on a non-lingual site.

 $language = $_REQUEST["language"]; $default_header="myheaderXXX.php"; switch ($language) { case "en": include("headerEn.php"); break; case "no": include("header.php"); break; default: include($default_header); } 

And then create these links:

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

To give a solution without changing your approach, you can do it as follows.

 <?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 save this value in a database or session.

+1
source

Try storing this value of $language in the session variable. When the page reload checks to see if the session variable is set or not.

If set, use $language

Note:

 $language = $_GET['language']; 
0
source

You cannot change a variable in PHP via html. PHP is a server server. HTML client interface

You can use GET variables to change it. This is the easiest way to do this.

0
source

You can implement the same code as this one. I edited your code.

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

this will solve your problem.

0
source

All Articles