Getting a user's language in PHP - php

I am trying to do localization for a site I'm working on at the moment and am doing something like this:
if(!isset($_SESSION['lang'])){
$_SESSION['lang'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}else if(isset($_GET['lang']) && !empty($_GET['lang'])){
$_SESSION['lang'] = $_GET['lang'];
}
This is fine and works as expected, however, sometimes there is no value for $_SERVER['HTTP_ACCEPT_LANGUAGE'], after a quick test of visitors to our site approximately 20% actually have a value and 80% do not.
Is there a better way to detect a user's language?

As suggested I ended up falling back to English in an else statement if I cannot determine the language

Related

PHP language redirection can't switch back

I have a very simple static one-page website, which I have available in English (default) and also in German - what I would like to achieve is to automatically redirect German users to the German version of the website which seems to work with the code I use here:
<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang){
case "de":
header("Location: http://www.website.net/de");
break;
}
?>
The problem now is that I still would like to give them the option to switch to English as well however once they click English they will always be redirected to German version of the site and are stuck with it. Is there a way to have this fixed and working properly?
You need another variable. You can do it with a URL param or a cookie, either way will get you what you want.

External language file

I have a little bit confusing problem.
I have website with multiple languages. For default labels and headings I made some external php file where I have variables with values for different languages.
For example, In file I have variable
$heading = "First Heading in English"
and variable
$heading = "First Heading in German"...
In session I have stored value for current language, and with if state I know what language variables to take.
My problem is next:
When I load my page for first time, all of fields where I call variables from external language file are empty...
And, when I refresh my page, variables are there, with right value....
Can someone help me with this problem??
I include external file before everything in my php file, with include function.
How do you include the file?
Perhaps first language variable is not saved in session yet.
It is always a good idea to check if language is not set you are going to use some default value i.e english.
if (!isset($language)) {
$language = 'en';
}
Modified this a little bit from what i have written a while ago...maybe this will help you a little bit.
$langSession = $_SESSION['lang'];
if(!isset($_SESSION['lang']){ // if the Session with language was not set
$browserlang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); // Get the browser setting language, tested it in firefox
if($browserlang == "de"){
$_SESSION['lang'] = "de"; // German
}elseif($browserlang == "nl"){ // Dutch
$_SESSION['lang'] = "nl";
}else{ // Else English
$_SESSION['lang'] = "en";
}
}
include('language.php');

PHP: A way to manually switch languages?

I have a website that has the following language switching algorithm:
First, it detects the default browser language (I do not know why? but Chrome always gives something like en-EN,ru,lv, so Chrome's default language always is English, it seems).
Then it writes the language value into a session variable lang and requests the desired string file (i.e. /assets/includes/en-US/strings.php);
And every string from this file is being included in the HTML code, so the pure HTML has not any plain text in.
Of course, a default language detection is not the reason to stop - I need a manual language switcher like links (LV | EN | RU). So, what id the possible (and maybe the best) way to switch the language and to overwrite the session variable after user clicks to the desired language?
The best way is the simpliest way :)
$langs = array('LV', 'EN', 'RU');
<?php foreach ($langs as $lang): ?>
<?=$lang;?>
<?php endforeach; ?>
so you give the user opportunity to change lang via GET in this example.
Overwrite the session to the sent request:
<?php
if(in_array($_GET['lang'], $langs) {
$_SESSION['lang'] = $_GET['lang']; // to prevent user to change its session to something you don't want to
}
?>
Afterwards you just interact with this session to display content.
You can use redirection, if you have each page written in different language:
(but I guess the logic how to interact with the language you have already implemented from the automatic language detection, but still... let me suggest some ways at fast?)
<?php
if (isset($_SESSION['lang']) && $_SESSION['lang'] !== 'EN') {
header("Location: mysite.com/".$_SESSION['lang']."/index.php");
exit;
}
?>
Or, you can use translation method.
All of your translations are in a database under columns with the same names as your $langs array.
So you output the content from this particular column:
SELECT lang_{$_SESSION['lang']} FROM translations WHERE string = '$string';

Auto detect language and redirect user

I am doing my own website and I managed to write some code that makes directs user to the language version according to the browser's language. Here is the script:
<?php
if ($_SERVER["HTTP_ACCEPT_LANGUAGE"] == "sv")
header("location: index.php");
if ($_SERVER["HTTP_ACCEPT_LANGUAGE"] == "pt")
header("location: pt/index.php");
else
header("location: en/index.html");
?>
I have put this in the index.php before the . It seems to be working because I am not in an English speaking country but my browser is in English and I am being redirected to the English version.
Is this correct? Is there a better/cleaner way to do this?
PHP 5.3.0+ comes with locale_accept_from_http() which gets the preferred language from the Accept-Language header.
You should always prefer this method to a self-written method as the header field is more complicated than one might think. (It's a list of weighted preferences.)
You should retrieve the language like this:
$lang = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
But even then, you won't just have en for every English user and es for Spanish ones. It can become much more difficult than that, and things like es-ES and es-US are standard.
This means you should iterate over a list of regular expressions that you try and determine the page language that way. See PHP-I18N for an example.
Well, I came across some problems with my code which is no surprise due to I am not a PHP expert. I kept therefore on searching for a possible solution and I found the following code on another website:
<?php
// Initialize the language code variable
$lc = "";
// Check to see that the global language server variable isset()
// If it is set, we cut the first two characters from that string
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
$lc = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// Now we simply evaluate that variable to detect specific languages
if($lc == "fr"){
header("location: index_french.php");
exit();
} else if($lc == "de"){
header("location: index_german.php");
exit();
}
else{ // don't forget the default case if $lc is empty
header("location: index_english.php");
exit();
}
?>
This did the job perfectly! I only had a problem left. There was no way to change language, even with direct links into another language because as soon as the page was loading, the php block would redirect me to the borwser's language. This can be a problem if you are living in another country and have for instance Swedish as a mother language but you have your browser in English because you bought your computer in the UK.
So my solution for this issue was to create folders with a duplicate version for every language (even the one for the main language) without this php code on the index.html (and therefore not index.php). So now my website is auto detecting the language and the user also has the option to change it manually in case of they want!
Hope it will help out someone else with the same problem!
I think your idea is great. May be help you shortest code:
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
header("location: ".$lang."/index.php");
That should work fine. You could also use http_negotiate_language and discusses here
Most useful this code
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if(file_exists('system/lang/'.$lang.'.php'))
{
include('system/lang/'.$lang.'.php');
}else{
include('system/lang/en.php'); //set default lang here if not exists translated language in ur system
}

Automatic Redirect Depending on Users Language

OBJECTIVE
I'm trying to accomplish an automatic redirect depending on the users language. I have a fully working code for that:
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
"da" => "http://www.fredrixdesign.com/",
"en" => "http://en.fredrixdesign.com/"
);
// Get 2 char lang code
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// Set default language if a `$lang` version of site is not available
if (!in_array($lang, array_keys($sites)))
$lang = 'en';
// Finally redirect to desired location
header('Location: ' . $sites[$lang]);
?>
This redirects the user to a Danish (da) version, which is the main/root website, if the user is Danish. If the user is German, English, Polish, etc. it redirects the user to a subdomain; en.fredrixdesign.com, which is an English version of the website.
But the problem occurs, when a Danish-user goes on my site. The code, located in the top of my header.php, keep getting executed, which means, it keeps creating the redirect, which finally forces the browser to create an error due to too many redirects. This makes sence.
QUESTION
My question is then; how would I go around modifying the above code, so it only executes the redirect once? If it just completed the redirect, it will simply continue to execute the site.
Well, I bet you can find a solution yourself if just think it over a bit.
All you need is to check if current domain meets desired language.
Just amend your array a bit
$sites = array(
"da" => "www.fredrixdesign.com",
"en" => "en.fredrixdesign.com"
);
and then add a condition for the redirect
if ($sites[$lang] != $_SERVER['HTTP_HOST']) {
header('Location: http://' . $sites[$lang] . '/');
exit;
}
that's all
You could set a cookie value, that tells you that you have already automatically redirected the user to a language-specific site. If that cookie exists, do not do the redirect again. You may also wish to consider the case where the user has cookies disabled.
You could do this with GeoIP + .htaccess, it's really easy to implement.
http://www.maxmind.com/app/mod_geoip
Something like this could do the trick (of course there are tons of heavy good solution but for two languages there is no harm to do simple things and improve later when needed):
function redirectIfUserIsNotOnTheGoodURLBasedOnHisLanguage()
{
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
"da" => "http://www.fredrixdesign.com/",
"en" => "http://en.fredrixdesign.com/"
);
// Get 2 char lang code
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// Set default language if a `$lang` version of site is not available
if (!in_array($lang, array_keys($sites)))
$lang = 'en';
if (($lang == 'da' && $_SERVER['SERVER_NAME'] == 'www.fredrixdesign.com') || // Danish people are on the right place
($lang == 'en' && $_SERVER['SERVER_NAME'] == 'en.fredrixdesign.com')) // Other people are on the right place
{
// no redirection
return;
}
// else redirect to desired location
header('Location: ' . $sites[$lang]);
exit(0);
}
redirectIfUserIsNotOnTheGoodURLBasedOnHisLanguage();

Categories