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';
Related
So I'm building a small multilingual (French + English) website and there is a little bug. I would like to remove the "english default" language in the code, so if a user picks french on one page, any page he will select afterwards will be in french and not be "back" to english. Same if the user picks english in the first place. But since there will be more french users, I would like it to be the default language on the home page.
The content is in folder with prefixes: fr_language.php and en_language.php
The lang.php file here
Links for FR or EN
Français
English
And the navigation
<ul>
<li><?php echo $lang['home']; ?></li>
<li><?php echo $lang['services']; ?></li>
<li><?php echo $lang['aboutus']; ?></li>
<li><?php echo $lang['contact']; ?></li>
</ul>
Thanks for your help!
EDIT:
Ok great, with your help it's working! In my "nav.php" include, I wrote this. Perhaps it's possible to do a cleaner version, haha! Any ideas? Thanks again!
Consider using the following approach/method:
if(isset($_GET['lang']) && $_GET['lang'] == "fr"){
// do something
} else {
// do something else
}
You should also be made aware of (XSS) Cross-site scripting.
Here are a few links to read up on:
http://en.wikipedia.org/wiki/Cross-site_scripting
http://www.sitepoint.com/php-security-cross-site-scripting-attacks-xss/
http://www.smashingmagazine.com/2011/01/11/keeping-web-users-safe-by-sanitizing-input-data/
You can further your research by using "XSS injection php" as keywords in your favorite search engine.
you need to keep the state of the language somewhere.
you will either have to pass it around with each request by
url parameter: page.php?lang=en
path: yourpage.com/en/page.php
or use a cookie to store it. you will get the cookie value passed with each server request
you can read the cookie through the $_COOKIE var. you can set it either in javascript or php
Personally, I recommend an on click for your language selector that will create a new PHP session and store the language.
The benefit of doing it this way is that you don't always have to have your language appended to the end of your URL. This will only happen each time a session has to be created, (so if you don't set a timeout then only when the computer restarts). Once the page redirects from the page that sets the language it doesn't have to $_GET anymore, but rather just check for an active session.
You will have to redirect the user to the page that has your PHP script and then set the language based on the what is sent in the URL. You could however, redirect after the script finishes back to the page the user was on (and load their new selected language).
HTML:
Français
English
PHP:
// intitially set language by your selector
<?php
session_start();
$_SESSION['language'] = $_GET['lang'];
?>
Now you could place your getter code on any page that gets included on all your pages (like a header or base page):
// check for the language
<?php
session_start();
if (isset($_SESSION['language'])) {
// now change the language of the page based on what it is
if ($_SESSION['language'] == "en") {
// change page language to english
} else {
// change page language to french
}
}
?>
It looks like you are using you are using a function called get_lang_id() to pull from the cookie and use that to load the language file.
The get_lang_id() function is currently defaulting to English:
function get_lang_id()
{
return ( isset( $_COOKIE['lang'] ) &&
strlen( $_COOKIE['lang'] ) == 2 &&
is_language_supported( $_COOKIE['lang'] ) ) ?
htmlspecialchars($_COOKIE['lang']) : 'en';
}
If you change the 'en' at the end to 'fr', it will change the default language file to the French version. Clicking either link will set a cookie, which will skip using the default.
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
}
I have a website which i want to create other language version.
I don't want to create folder for each language. I was wondering it
it's possible to add a combobox on each page or on the main one
so that user can setup the language then using php i will
check the option and show the right version. Any suggesting
to achive that?
If you have a combobox, when the user submits it, store the language in the session (session_start(); has to be called) with $_SESSION['lang'] = $_POST['lang'];. I'd advise you to whitelist languages as such:
session_start();
// define language whitelist
$allowedLangs = array('en', 'de');
// only store the new user language if it's an allowed one
if (isset($_POST['lang']) && in_array($_POST['lang'], $allowedLangs)) {
$_SESSION['lang'] = $_POST['lang'];
}
// define the user language based on session data or use 'en' as default if not available
$userLang = isset($_SESSION['lang']) ? $_SESSION['lang'] : 'en';
// parse some language file according to the language
$translations = // TODO load some file with $userLang here
Of course you should adjust this to your own project and environment. For translation files, you can use a plain PHP file that returns an array like such:
<?php
// en.php
return array(
'some.key' => 'Translation',
);
Then if you include that file, the return value of the include will be the array, so in the above code you could do:
$translations = include 'translations/'.$userLang.'.php';
You then have to output all your text through this $translations variable, like echo $translations['some.key'].
if you wanted to use cookies... in the lang files you would include an array of words or content to use.
<?php
if($_GET['language']){
$lang = (string)$_GET['language'];
setcookie("lang", $lang, time()+3600);
header('Location: '.$_SERVER['PHP_SELF']);
die();
}elseif(!isset($_COOKIE['lang'])){
$lang='en';
}else{$lang=$_COOKIE['lang'];}
switch($lang){
case "en":
include('./lang/en.php');
break;
case "fr":
include('./lang/fr.php');
break;
case "pol":
include('./lang/pol.php');
break;
default:
include('./lang/en.php');
break;
}
?>
you mean something along the lines of
if ($_GET['language']) {
include $_GET['language'] . ".php";
}
and then save the languages in a php-file with there name, or a function depending on what you want to do with it
hey for language version.
have languages in combobox.
maintain your current language in session.
When u change language call an ajax call Update the changed language into session and reload the page.
display page view with respect to session stored language.
thats it........
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.
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) ;
?>