我有一个网站,自动检测国家/地区,并根据国家/地区设置语言,但用户无需手动更改。
如何将以下代码添加到其下方的代码中,以确保我可以输入以下链接:http://example.com/index.php?lang=de
//Code I want to integrate with the code below
switch ($lang) {
case 'en':
$lang_file = 'lang.en.php';
break;
case 'de':
$lang_file = 'lang.de.php';
break;
default:
$lang_file = 'lang.en.php';
}
//Main Code Below
<?php
function visitor_country()
{
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
$result = "Unknown";
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
$ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));
if($ip_data && $ip_data->geoplugin_countryName != null)
{
$result = $ip_data->geoplugin_countryName;
}
return $result;
}
session_start();
header('Cache-control: private'); // IE 6 FIX
if (isSet($_GET['lang'])) {
$lang = $_GET['lang'];
// register the session and set the cookie
$_SESSION['lang'] = $lang;
setcookie('lang', $lang, time() + (3600 * 24 * 30));
} else if (isSet($_SESSION['lang'])) {
$lang = $_SESSION['lang'];
} else if (isSet($_COOKIE['lang'])) {
$lang = $_COOKIE['lang'];
} else {
$lang = 'en';
}
if(visitor_country() == "Germany") {
$lang_file = 'lang.de.php';
//echo "Germany";
} else {
$lang_file = 'lang.en.php';
//echo "Not in Germany";
}
include_once 'languages/' . $lang_file;
?>
任何建议?
答案 0 :(得分:2)
将自动检测置于您的开关的default:
情况下:
$lang = null;
if (isset($_GET['lang'])) {
$lang = $_GET['lang'];
// register the session and set the cookie
$_SESSION['lang'] = $lang;
setcookie('lang', $lang, time() + (3600 * 24 * 30));
} else if (isset($_SESSION['lang'])) {
$lang = $_SESSION['lang'];
} else if (isset($_COOKIE['lang'])) {
$lang = $_COOKIE['lang'];
}
switch ($lang) {
case 'en':
$lang_file = 'lang.en.php';
break;
case 'de':
$lang_file = 'lang.de.php';
break;
default:
if(visitor_country() == "Germany") {
$lang_file = 'lang.de.php';
//echo "Germany";
} else {
$lang_file = 'lang.en.php';
//echo "Not in Germany";
}
}
答案 1 :(得分:0)
if(isset($_GET['lang'])){
// get variable 'lang' is defined.
$lang = $_GET['lang']
}
您在此处的代码中重置了以下$lang_file
的值:
if(visitor_country() == "Germany") {
$lang_file = 'lang.de.php';
//echo "Germany";
} else {
$lang_file = 'lang.en.php';
//echo "Not in Germany";
}
如果删除该代码则应该有效。