Reputation: 699
I've got a website where the country is detected automatically and a language is set according to the country, but the users have no manual way to change it.
How can I add the following code to the code below it to make sure I can enter the following link: 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;
?>
Any Suggestions?
Upvotes: 0
Views: 203
Reputation: 780698
Put the auto-detection in the default:
case of your switch:
$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";
}
}
Upvotes: 2
Reputation: 11661
if(isset($_GET['lang'])){
// get variable 'lang' is defined.
$lang = $_GET['lang']
}
you reset the value of $lang_file
below in your code here :
if(visitor_country() == "Germany") {
$lang_file = 'lang.de.php';
//echo "Germany";
} else {
$lang_file = 'lang.en.php';
//echo "Not in Germany";
}
if you remove that code it should work.
Upvotes: 0