问题
I'm trying to set a multilungal website using cookie. Everything's fine but I'm having trouble setting a default language. I'm getting an error "undefined index" in php when i get to the root website without parameter.
<?php
if (isset ($_COOKIE['CHOIXlang']) && $_GET['langue'] != 'fr' && $_GET['langue'] != 'en' && $_GET['langue'] != 'es')
{
$langue = $_COOKIE['CHOIXlang'];
}
else if ($_GET['langue'] == 'en' || $_GET['langue'] == 'fr' || $_GET['langue'] == 'es')
{
$langue = $_GET['langue'];
set_cookie($langue);
}
else
{
$langue = substr($HTTP_SERVER_VARS['HTTP_ACCEPT_LANGUAGE'],0,2);
set_cookie($langue);
}
?>
<?php
function set_cookie($langue)
{
$expire = 365*24*3600;
if (setcookie("CHOIXlang", $langue, time() + $expire) != TRUE)
{
}
else
{
setcookie("CHOIXlang", $langue, time() + $expire);
}
}
?>
And in the body :
<?php
if ($_GET['langue'] == "fr" || $langue == "fr")
{
include('lang/fr-lang.php');
}
elseif ($_GET['langue'] == "en" || $langue == "en")
{
include('lang/en-lang.php');
}
elseif ($_GET['langue'] == "es" || $langue == "es")
{
include('lang/es-lang.php');
}
?>
What did I miss to set default language when the website opens ?
Thank you
回答1:
You need to check if your get parameter langue is set: isset($_GET['langue'])
<?php
if (!isset($_GET['langue'])
{
include('lang/default-lang.php');
}
elseif ($langue == "fr")
{
include('lang/fr-lang.php');
}
elseif ($langue == "en")
{
include('lang/en-lang.php');
}
elseif ($langue == "es")
{
include('lang/es-lang.php');
}
?>
Also in you need to change this line : $langue = $_GET['langue'];
to this:
if (isset($_GET['langue']))
$langue = $_GET['langue'];
UPDATE
You cannot access any GET value that does not exist. First you need to check if it was set. isset($_GET['langue'])
returns true if the parameter was set, so just use this check once at the beginning of your code.
I'd suggest this:
$langue = "";
if (!isset($_GET['langue']){
$langue = $_GET['langue'];
}
then use only $langue
instead of $_GET['langue']
.
回答2:
Set Default Lan may should be like this
if (@$_GET['lang'] == 'en') include('en-lang.php');
else include('fr-lang.php');
Use $_GET for it:
This is a little long winded but might be a slightly better approach:
<?php
session_start();
if (isset($_SESSION['lang'])) $lang = $_SESSION['lang'];
if (isset($_GET['lang'])) {
$lang = preg_replace('/[^a-zA-Z]/', '', $_GET['lang']);
$_SESSION['lang'] = $lang;
}
if (!isset($lang)) $lang = 'fr';
$langfile = $lang . '-lang.php';
if (file_exists($langfile)) include ($langfile);
else include('fr-lang.php');
?>
来源:https://stackoverflow.com/questions/21386670/set-default-lang-using-php