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');
Related
I start today in creating a multi-language system for my site.
To do so I created my two language files then created my switch that here below:
link
To call the file I created simple links
<p>EnglishFrançais</p>
When I'm on the home page and I click on "English" translation that do well but if I click on another link to my site I automatically revert to French when I should remain in English!
How can I fix this problem?
Your problem is that you always read the GET variable for language and if it's missing, you switch back to the default one (French), which makes storing it inside a session variable - useless.
You should either add ?lang=XX in all the links and remove the $_SESSION, or you should make the following changes in order to use the session variable:
}else {
$_SESSION['lang'] = 'fr';
include('french.php');
$langage=$_SESSION['lang'];
}
to:
}else {
if(isset($_SESSION['lang'])){
if($_SESSION['lang'] == 'fr'){
include('french.php');
}else{
include('english.php');
}
}else{
$_SESSION['lang'] = 'fr';
include('french.php');
$langage=$_SESSION['lang'];
}
}
That way, if no language alteration is requested, your script will check if it has a stored language variable, before switching to the default one.
Ideally you should use case instead of IFs if you have more than 2 languages.
}else {
switch($_SESSION['lang']){
case 'en':
include('english.php');
break;
case 'es':
include('spanish.php');
break;
//insert other language cases here
default:
include('french.php');
break;
}
}
My advice is, the third option. Many sites have a separate directories for each of languages and look like this: www.domainname.ext/ for the default language and www.domainname.ext/xx/ for the other languages, where xx is the abbreviation of the language (en for English and etc.)
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';
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........
langauage web. I set 3 links, Français... (href=changeLanguage.php?lang=fr,es,en)
changLanguage.php
session_start();
if(isset($_SESSION['bckTo']) && isset($_GET['lang'])){
$lang = preg_replace('/[^a-z]/','',trim($_GET['lang']));
#TODO
#More vlidation ...
$full_url = $_SESSION['bckTo'];
$full_url = str_replace(array('&lang=en','&lang=es','&lang=fr'),'',$full_url);
header('Location: '.$full_url.'&lang='.$lang.'');
}
$_SESSION['bckTo'] save the current URL for example: mysite.com/index.php?id=x&n_d=y
The problem is, the header translate the URL to: mysite.com/index.php?id=x&n_d=y&lang=en.
Any idea will be appreciate
Why not just set the language in session instead of via GET? Then you just have to put a link to change the language and and then redirect to the page. This would probably be best, given that you are already using sessions.
Example:
English
On the changeLanguage:
//code up here
if (isset($_SESSION['bckTo') && isset($_GET['lang'])) {
// $lang code here
$_SESSION['lang'] = $lang;
header('Location: ' . $_SESSION['bckTo']);
}
Then you would just need to change your language checking / displaying code to check the session variable rather than the GET (on the actual pages).
Running html_entity_decode will convert those HTML entities back into ampersands.
http://us2.php.net/manual/en/function.html-entity-decode.php