I have set up a basic script for simple multi-language support. My problem is that if the user types manually on the url his own GET params it's showing error(of course since it doesn't lead anywhere correctly). For example I have set up an array for 'en' and 'el' but if the user types manually 'de' since this language is not in my array it will lead to an error page of undefined index. I want to redirect the user to index.php with the default language selected.
Here is my index.php
<?php
include('lang.php');
set_lang();
$current = $_SESSION['lang_ses'];
?>
<html>
<body>
<div style="height:100px; background-color:red; color:black;">
<a href="index.php?lang=en">ENG</a>
<a href="index.php?lang=el">EL</a>
</div>
<div style="height:400px; background-color:gray; color:white;">
<h2><?php echo $langarray[$current]['service1']; ?></h2>
<h2><?php echo $langarray[$current]['service2']; ?></h2>
<h2><?php echo $langarray[$current]['service3']; ?></h2>
</div>
</body>
</html>
Here is my script lang.php
<?php
function set_lang() {
session_start(); // Starting php session
$default = 'en'; // Here you can set with which language the website should start.
if(!isset($_SESSION['lang_ses'])) { // Setting up chosen language or load default language
if(isset($_COOKIE['lang'])) {
$_SESSION['lang_ses'] = $_COOKIE['lang'];
} else {
$_SESSION['lang_ses'] = $default;
}
}
if(isset($_GET['lang'])) {
$_SESSION['lang_ses']=$_GET['lang'];
setcookie('lang',$_GET['lang'],time()+24*3600); // writing cookie
}
}
$langarray = array(
'en'=>array(
'service1'=>'Health',
'service2'=>'Beauty',
'service3'=>'Strength'
),
'el'=>array(
'service1'=>'Υγεία',
'service2'=>'Ομορφιά',
'service3'=>'Δύναμη'
)
);
?>
if (!in_array($_GET['lang'], ["en","el"])) { // PHP 7
header('Location: /index.php');
}
Another way is to set a default value for the $_SESSION['lang_ses']
on top of your script before running set_lang()
function.
$_SESSION['lang_ses'] = "en";
set_lang();
use a comparison like this inside your function
if (!in_array($_GET['lang'], ["en","el"])) { // PHP 7
$defaultLangCode = $_SESSION['lang_ses'];
} else {
$defaultLangCode = $_GET['lang'];
}
... continue your script using $defaultLangCode
, this way there is no need for redirect. You will have as default language for my.site/de
your English page.