问题描述
我正在尝试使用Cookie设置一个多语言网站。一切都很好,但是我无法设置默认语言。
当我不带参数进入根网站时,在php中出现错误未定义索引。
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);
}
}
?>
在体内:
<?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 ?
谢谢
推荐答案
您需要检查是否设置了get参数语言: isset($ _ GET ['langue'])
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');
}
?>
此外,您还需要更改以下行: $ langue = $ _GET ['langue'];
改为:
Also in you need to change this line : $langue = $_GET['langue'];
to this:
if (isset($_GET['langue']))
$langue = $_GET['langue'];
更新
您无法访问任何GET值那不存在。您需要检查它是否已设置。如果设置了参数, isset($ _ GET ['langue'])
将返回true,因此只需在代码开头使用一次此检查即可。
我建议这样做:
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'];
}
然后仅使用 $ langue
而不是 $ _ GET ['langue']
。
这篇关于使用PHP设置默认语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!