How to create multi language main menu in html/php script
now i have
<li>
<a href="{url p='poceni-letalske-karte.html'}">
<span>{t t="Letalske Karte"}</span>
</a>
</li>
and
<option value='EN'>English</option> which it go to mysite.com/EN
i want when user select English language EN code it also change main menu text how to do that ?
This is website Letalske karte
I found this script http://www.bitrepository.com/php-how-to-add-multi-language-support-to-a-website.html
But i don't know how to set to /EN/ as now in this script is set to index.php?lang=en
My Approach would be to do the following:
Step 1: Setup a folder tree structure like this:
Languages
-en
-lang.en.php
-fr
-lang.fr.php
-de
-lang.de.php
keep making new folders with all the other languages you want to support
Step 2: Create our language files, i will start with languages/en/lang.en.php
<?php
$lang['label'] = 'Value for this label';
$lang['firstname'] = 'First Name';
$lang['lastname'] = 'Last Name';
$lang['phone'] = 'Phone';
// ETC
?>
you would repeat this for every other language, ill do fr for example languages/fr/lang.fr.php . NOTE how the labels stay the same in english
<?php
$lang['label'] = 'Valeur pour ce label';
$lang['firstname'] = 'Prénom';
$lang['lastname'] = 'Nom de famille';
$lang['phone'] = 'Téléphone';
// ETC
?>
Step 3: Check if the user has requested a language change, via a url variable
<?php
// Start a Session, You might start this somewhere else already.
session_start();
// What languages do we support
$available_langs = array('en','fr','de');
// Set our default language session
$_SESSION['lang'] = 'en';
if(isset($_GET['lang']) && $_GET['lang'] != ''){
// check if the language is one we support
if(in_array($_GET['lang'], $available_langs))
{
$_SESSION['lang'] = $_GET['lang']; // Set session
}
}
// Include active language
include('languages/'.$_SESSION['lang'].'/lang.'.$_SESSION['lang'].'.php');
?>
Step 4: you can access your language parts like so and it would change based on what language file is loaded.
<?php
echo $lang['firstname'];
?>
hope this helps get you started as an idea
Used the above code, but session is overwritten every load to EN, so changed it to
<?php
// Start a Session, You might start this somewhere else already.
session_start();
// What languages do we support
$available_langs = array('en','zh-cn','es');
if(isset($_GET['lang']) && $_GET['lang'] != ''){
// check if the language is one we support
if(in_array($_GET['lang'], $available_langs))
{
$_SESSION['lang'] = $_GET['lang']; // Set session
}
}
// Set our default language session ONLY if we've got nothing
if ($_SESSION['lang']=='') {
$_SESSION['lang'] = 'en';
}
// Include active language
include('languages/'.$_SESSION['lang'].'/lang.'.$_SESSION['lang'].'.php');
?>
If your language file is really long, you could break it up by page by adding this above the language include:
// for login page
$textpart = 'login';
and have the language page split up the array thusly
<?php
switch ($textpart) {
//login page
case 'login':
$lang['label'] = 'Value for this label';
$lang['firstname'] = 'First Name';
$lang['lastname'] = 'Last Name';
$lang['phone'] = 'Phone';
break;
//home page
case 'home':
// ETC
}
// All pages
$lang['title'] = 'Title';
// ETC
?>
LM PHP (Language management PHP)
Multi-language management and support for the PHP.
Sample :
<?php
include "LMPHP.php";
/////////////////////////////
$langs = new LMPHP();
$langs -> language_add("en","English");
$langs -> language_add("fr","Germany");
$langs -> language_active("en");
$langs -> word_add("Bye","Good Bye!");
$langs -> word_add("HowAre");
$langs -> language_active("fr");
$langs -> word_add("Bye","Au revoir!");
print_r( $langs -> words );
echo $langs -> word_get("Bye");
Code Repository :
https://github.com/BaseMax/LMPHP
Full Sample Code :
https://github.com/BaseMax/LMPHP/blob/master/Sample.php
Related
My website by default is in English
But I can change the language, when a visitor visits our website with a url of a news item in Spanish:
example.com/es/news/718/url-title-article/
The url given as an example is a news in Spanish since the first folder or directory is named "es" example.com/es/news/718/url-title-article/ -> es
And, that's where the trick comes, since I have a function that allows me to obtain the name of the first folder or directory and if it matches with the given parameters, it should set a cookie with the language of that url, in this case Spanish -> "es".
if($FOLDER_LANG === "es" || $SUBDOMAIN_LANG === "es") {
setcookie ('language', 'es', time()+60*60*24*365, '/', 'example.com');
}
if(isset($_COOKIE['language'])){
if($_COOKIE['language']==='en'){
$WEBSITE_TITLE = " | WebSIte EN";
$LANG = 'en';
$language = "en";
}elseif($_COOKIE['language']==='es'){
$WEBSITE_TITLE = " | WebSite ES";
$LANG = 'es';
$language = "es";
}
} else {
$WEBSITE_TITLE = " | WebSite DEFAULT EN";
$LANG = 'en';
$language = "en";
}
But the problem, is that I have to reload the page to see the changes of the new language added to the site.
So how can you solve it without having to reload the site.
You need to write the logic which determines the language so it doesn't depend on the cookie.
So, before, where you might have had something like:
$language_data = get_i18n_data( $_COOKIES['language'] );
You would instead have something like:
function get_language() {
if($FOLDER_LANG === "es" || $SUBDOMAIN_LANG === "es") {
setcookie ('language', 'es', time()+60*60*24*365, '/', 'example.com');
return 'es'
}
return $_COOKIES['language'];
}
$language_data = get_i18n_data( get_language() );
The reason for refresh being needed is that $LANG and $language is set by an existing cookie and not the new one.
Analysing your code:
if($FOLDER_LANG === "es" || $SUBDOMAIN_LANG === "es") {
setcookie ('language', 'es', time()+60*60*24*365, '/', 'example.com');
}
Here, it's setting the cookie only in the header. It is not accessible until the page is reloaded.
One option is to add the following in the if condition:
$LANG = 'es';
$language = "es";
The rest of your code then reads existing cookies so this is what will load on the same page even if the cookie is set just before it:
A better way in my opinion is to keep it simple and expandable by using variable $language to drive the data:
$language = 'en'; //this is default
if(isset($_COOKIE['language'])){
$language = $_COOKIE['language'];
}
//now check if current $language is different to folder
if($FOLDER_LANG != $language || $SUBDOMAIN_LANG != $language) {
//this is condition depends on your variables. You might need && if both conditions should be met or modify as required
//set the language for this page (so no need for refresh and also set the cookie
$language = $FOLDER_LANG ? $FOLDER_LANG : $SUBDOMAIN_LANG; //sets to folder or sudomain language code if $FOLDER_LANG is empty. You can switch the two folders to priotorise the latter.
//now set the cookie
setcookie ('language', $language, time()+60*60*24*365, '/', 'example.com');
}
//now set the the title and the extra variable $LANG (you probably should choose one variable to use)
$WEBSITE_TITLE = " | WebSite . strtoupper($language)";
$LANG = $language;
Now you can support more languages and also won't need to refresh
Please excuse my English language skills.
I have a Homepage with a language exchange in the following included common.php
<?php
session_start();
header('Cache-control: private');
if(isSet($_GET['lang']))
{
$lang = $_GET['lang'];
$_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 = 'de';
}
switch ($lang) {
case 'en': $lang_file = 'lang.en.php'; break;
case 'de': $lang_file = 'lang.de.php'; break;
case 'ru': $lang_file = 'lang.ru.php'; break;
case 'fr': $lang_file = 'lang.fr.php'; break;
default: $lang_file = 'lang.de.php';
}
include_once 'lang/'.$lang_file;
?>
Now I would like to implement on my website a Mini-Blog with Flat Files and use the following Code
<?php
define("DEFAULT_LANGUAGE", "lang=de");
session_start();
$languages = ["de", "en", "fr", "ru"];
if( isset($_GET["lang"]) ){ $lang = filter_input(INPUT_GET, "lang", FILTER_SANITIZE_STRING);
if( !in_array($lang, $languages) ){ $lang = DEFAULT_LANGUAGE; }
$_SESSION["language"] = $lang;
}
function get_lang() { return isset($_SESSION["language"]) ? $_SESSION["language"] : DEFAULT_LANGUAGE; }
function get_post_names() {
static $_cache = [];
if(empty($_cache)){ $_cache = array_reverse(glob(__DIR__ . '/posts/' . get_lang() . '/*.php')); }
return $_cache;
}
function print_posts() { $paths = get_post_names();
foreach( $paths as $path ){ $content = file_get_contents($path);
echo "<div class='post'>\n";
echo "<p>{$content}</p>\n";
echo "</div>\n\n";
}
}
?>
<?php print_posts(); ?>
For the blog posts, there is a folder [posts] in which subfolders (de, en, fr, ru). In these subfolders there are, depending on the language, for example: "examplepost.php" in whose blog posts have been written.
The language selection works without any problems. But I want that when a user selects a different language, then the Blog automatically reads the voice corresponding folder of the blog and containing the outputs files.
The Problem is that there are two Sessions. This leads to errors! My question would be: How can I merge everything together in a Session or how can I connect the two Sessions without conflicts, so it works both (the language of the site and the output of the files in the folders of the visitors selected language for the Blog posts).
Many thanks in advance to all of you for your help and suggestions! Greeting
You do not need two sessions to hold the same variable ($lang).
What you can do is something like this:
session_start();
// check/set default language session
if (!isset($_SESSION["language"])) {
$_SESSION["language"] = DEFAULT_LANGUAGE;
}
if ($isset($_GET['lang']) && in_array($_GET['lang'], $languages) ){
$_SESSION["language"] = $_GET['lang'];
}
// execute more code
$lang_file = 'lang.'.$_SESSION["language"].'.php';
include_once 'lang/'.$lang_file;
andrew
I think I have expressed myself wrong.
The common.php for the language exchange, is responsible and should be retained. I just need a function in the common.php what are the same functions as in the other mentioned Script. It must be possible, that ...
is changed to the selected language on the website
And at the same time also referred to the sub-folder of the blog ("posts").
The Structure
[root]
|_ acp ........ admin-center
|_ css ........ css styles
|_ img ........ graphics
|_ inc ........ includes files
|_ func ....... function files (i.e. common.php)
|_ js ......... js files
|_ lang ....... language files
|_ posts ...... for the Blog Postings
|_ [de] [en] [fr] [ru]
In the last Folders are .php files witch, depending on the language selection has been selected via the common.php at the same time with the common.php also the files of the [posts] folder of the blog and displayed to be read.
In short ... 1) depending on the language in the language file redirect - AND - 2) in addition to the sub-folder of the [posts] folder and the contained files to be read and the contents of the files output.
Help please organize bi-lingual website.
So first there are two files eng.php, es.php and they will be stored in translation site.
example:
$lang['hi'] = 'Hi';
How can I organize further language choice on the site and record information about the language in cookies?
You can have two files like this.
Source of en.php:
$lang = array(
'hi' => 'Hi'
);
Source of es.php:
$lang = array(
'hi' => 'Hello'
);
And for the main content file, the source should be this way:
<?php
session_start(); // Make sure you initialize cookies / session
$allowedLangs = array('en', 'es'); // Array with allowed values
if(isset($_SESSION['lang'])) { // If already user had stored language in session
include $_SESSION['lang'] . ".php";
} elseif(isset($_GET['lang']) && in_array($_GET['lang'], allowedLangs)) { // If user had requested like index.php?lang=en
include $_GET['lang'] . ".php";
$_SESSION['lang'] = $_GET['lang']; // Update the session with the language
} else { // If user is visiting for the first time, then...
include "en.php";
}
echo $lang['hi'];
?>
<?php
if(!isset($_COOKIE['lang'])){
?>
Choose Language...
ESENG
<?php
} else {
if($_COOKIE['lang']=='es'){
header("location:es.php");
}
elseif($_COOKIE['lang']=='eng'){
header("location:eng.php");
}
}
?>
es.php // eng.php
<!--Your Content-->
<?php
setcookie("lang","es/eng",time()+SECONDS_YOU_WANT)
?>
I'm building multiple language web and found problem. My language is changing depending on session variable and on first load the session is empty,only after refreshing the page it gets the right session variable. How to set the variable before the page load? This is the code :
session_start();
$available_langs = array('en','rus');
if ($_SESSION['lang']=='') {
$_SESSION['lang'] = 'en';
}
if(isset($_GET['lang']) && $_GET['lang'] != ''){
if(in_array($_GET['lang'], $available_langs))
{
$_SESSION['lang'] = $_GET['lang'];
}
}
include('language/'.$_SESSION['lang'].'.php');
session_start();
// Direct override beats session
$lang = $_GET['lang'] ?: $_SESSION['lang'];
$available_langs = array('en','rus');
// If the requested language isn't available, or not provided, fall back to first
if(!in_array($lang, $available_langs))
$lang = $available_langs[0];
// Store it in the session and include the template
$_SESSION['lang'] = $lang;
include 'language/'.$lang.'.php';
I have a web site made in 3 languages, but will (maybe) be expanded.
So I created a table on the database where I insert the languages of the Website.
As index.php I have a script. If the URI detected is "/" the script redirects to /language/index.php.
I'd like now to have a script which dinamically redirects based on HTTP_ACCEPT_LANGUAGE.
My problem is that, the following script I made works only with the first foreach run.
$abbr = $link->query("SELECT abbr AS langs FROM LANGS");
while($langs_db = mysqli_fetch_array($abbr)){
$site_langs[] = $langs_db['langs'];
}
$client_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
foreach($site_langs as $lang){
switch($client_lang){
case $client_lang == $lang:
header("location: http://www.mysite.com/$lang/index.php");
break;
default:
header("location: http://www.mysite.com/$lang/index.php");
break;
}
}
I thought a solution like:
case $client_lang == $lang:
$find "location: http://www.mysite.com/$lang/index.php";
break;
default:
$not_find = "location: http://www.mysite.com/$lang/index.php";
break;
And then:
if($find != ''){
header($find);
}else{
header(not_find);
}
But I'm not sure this it's a good idea...
Thank you!
// Set the default language as a fall back
$default_lang='en';
// Have an array with all languages your site supports
$langs=array('en', 'es', 'pt', /* etc... */);
// Query the browser's first preferred language
$client_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// See if the language is supported otherwise redirect use the default one
$client_lang = (in_array($client_lang, $langs) ? $client_lang : $default_lang);
header("Location: /$client_lang/index.php");
Alternatively though you may want to consider gettext:
http://php.net/manual/en/book.gettext.php