Auto detect language and redirect user - php

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
}

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';

multilingual php script question

I have this PHP script. It's the only one that really worked to me:
<?php
/*Check_if_user_has_changed_language: */
if(isset($lang)){/*If_so:*/
setcookie("ling",$lang,time()-60*60*24*365,"/",".sayip.info",0);/*Wipe_previous_cookie*/
setcookie("ling",$lang,time()+60*60*24*365,"/",".sayip.info",0);/*Whatever_the_means_lang_has_been_stored,_store_latest_lang_in_new_cookie:*/
//echo "<script language=\"JavaScript\">alert('Selected language=$lang')</script>";/*UnComment_to_check*/
}else{/*If_user_has_NOT_changed_language:*/
if(isset($_COOKIE['ling'])){/*Check_if_user-language_cookie_is_set._If_so:*/
$lang=$_COOKIE['ling'];
setcookie("ling",$lang,time()-60*60*24*365,"/",".sayip.info",0);/*Wipe_previous_cookie*/
setcookie("ling",$lang,time()+60*60*24*365,"/",".sayip.info",0);
//echo "<script language=\"JavaScript\">alert('Cookie language=$lang')</script>";/*UnComment_to_check*/
}else{/*If_user-language_neither_selected_nor_in_cookie,_choose_browser_language:*/
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
setcookie("ling",$lang,time()+60*60*24*365,"/",".sayip.info",0);
//echo "<script language=\"JavaScript\">alert('Your browser language=$lang')</script>";/*UnComment_to_check*/
}
}
?>
First the code detects the language of the user's browser. That's ok.
Then stores the info in a cookie. That's ok.
Well in this piece of code its everything ok. What I really need is to create an option for visitors change the language. I was thinking something like linked flag images so when someone click on the flag it changes the language.
Can someone explain to me through an example or even a clean, full solution? My skills in PHP are poor.
Thanks in advance.
I would put the selected language in the URL, e.g http://example.com/en/foo/bar. This makes the selected language transparent and easy to change.
i would put to if i knew how to lol...Since i got this script working after testing more or less 10 different scripts, im not like falling back, just need an example in how to put flags and when someone click on the flag it changes de value of the cookie...
I'm not sure if I got your question right
if your gonna place a link for each language in your page, make the link something like
http://www.example.com/?lang=jp
then in the php code before the script that you posted add
if (isset($_GET['lang'])) $lang = $_GET['lang'];
is this what you ment?
A more elegant solution may be to check the user's headers. Most browsers will allow users to set their preferred language in preferences. This in turn sends an HTTP header with the request. The header looks like this.
Accept-Language : en-us,en;q=0.8,ar-ly;q=0.5,id;q=0.3
The value is a comma-delimited list of accepted languages, ordered by preference ( the q=x part is the preference). This way, you can automatically detect what language the user has opted to see the web, and display it if you have it.

Language neutral entry pages

My old web site has an index.html page … nothing strange! Everything is fine.
The new web site has an english and a french version, so the new index is index.php?lang=eng…. That makes sense.
I don’t like to make a front page that will say “english” or “french”. But that’s not good for ranking or seo.
So the question is: How do I manage to get a default index.php with request (?lang=eng) to become the front page?
domain.com/en/index.php
domain.com/fr/index.php
Use url rewriting with regular expressions (mod_rewrite, ISAPI, whatever) to handle requests to relevant pages so
domain.com/en/index.php REWRITE TO domain.com/index.php?lang=en
domain.com/fr/index.php REWRITE TO domain.com/index.php?lang=fr
This way your pages are two seperate pages to search engines but handled via one gateway in code. I'm not a regex expert but it would be a very simple regex I would imagine
I'm not sure I understand the question. It seems to have two parts:
How to provide a default language of English:
$lang = empty($_GET['lang']) ? "eng" : $_GET['lang'];
Do you also have a problem of where to put the English/Francais links so search engines don't ding you? I wasn't aware of this problem.
It might also help to let us know if you're using a CMS, and if so which one.
Unless I'm misunderstanding the question, in index.php, when you check the language, put something like this:
$lang = #$_GET['lang'];
if ( empty($lang) ) $lang = 'eng';
Just put an argument in the php code that says :
if (lang == "") // haven't done php in a while so the syntax is probably wrong
{
lang = "eng";
}
In other words, if there isn't an argument on the lang variable, you can just set it to be eng automatically, and so the first page will default to English every time, unless told otherwise.
Just make the default english and offer an option on the index page to change to french? This, of course, depends on what language most of the visitors speak, which isn't all that hard to figure out with visitor logs.
I would use a neutral URL for entry, such as:
http://example.com/foo/bar
On this page I would do some language negotiation or simply ask the user for the prefered language. Then I can redirect to the language specific URL:
http://example.com/en/foo/bar
what do you think about that solution
<?php
$lang = $_GET['lang'];
if ( empty($lang) ) $lang = 'fra';
header( 'Location: http://acecrodeo.com/new/01-acec.php?lang='.$lang) ;
?>

Categories