Multilingual Site - Redirection - php

I am trying to implement a language based redirection. Our site has sub-domains for different languages ie es.domain.com // de.domain.com etc. What i am trying to do is include the following code on all pages
<?php
$lng = array( 'en'=>'www', 'de'=>'de'); // more languages
$defaultLang = 'en'; // Index of the default (and fallback) language
$cookieName = "_dmLang"; // Set up the cookie name
$lang = trim(substr($_GET['lang'], 0, 2));
if (empty($lang)) $lang = trim($_COOKIE[$cookieName]);
if (empty($lang)) $lang = trim(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
if (empty($lang) || empty($lng[$lang])) $lang = $defaultLang;
setcookie($cookieName, $lang, time()+3600*24*30);
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://".$lng[$lang].".domain.com" . $_SERVER['REQUEST_URI']);
?>
The language will change when you call /?lang=de
Are there any server/load implications when using this code? Is there a better way to implement this?

Related

I can't set a php cookie

I made a php script that allows me to switch the language of my website and for that, I used a cookie called lang to store the user's language prefer but I don't Know why this cookie can't be set as I can't find it in the chrome developer tap .. Although I made this script also with session variable in case cookie isn't set, it doesn't work either, as it shifts the language whenever I change the page
this is my PHP script
<?php
session_start();
if(isset($_GET['lang'])) {
$lan = $_GET['lang'];
$_SESSION['lang'] = $lan;
setcookie("lang", $lan, time() + (3600 * 24 * 30), '/');
} else if (isset($_SESSION['lang'])) {
$lan = $_SESSION['lang'];
} else if (isset($_COOKIE['lang'])) {
$lan = $_COOKIE['lang'];
} else {
$lan = 'en';
}
include "languages/" . $lan . ".php";
?>
I have two files in that language folder en.php and ar.php and each one contains an array with translation like below
<?php
$lang = array(
"Give" => "Give",
"Blood" => "Blood",
"Register as a donator" => "Register as a donator",
"Search for a donator" => "Search for a donator"
I include my script in all my site's pages
here is my chrome developer tap screen shot
any thoughts?
Thanks for helping in advance :)

How to automatically reflect changes when adding PHP cookie?

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

Language based on HTTP_ACCEPT_LANGUAGE and database languages

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

best way to change current site language

i am creating a website by two language with php. to change language of pages , i create to link like this:
FA|EN
this two link is on a page named header.php that includes on some page.but in some pages is some parameters that send via URL . So that two link are not true and they Should be as follows:
FA|EN
my Question is how i create a dynamic links for all page Even if have some parameters.
You need to store the value in a global key, preferable php's $_SESSION
in the beginnen of your page you can then check with the following :
session_start(); // if not started already
$possible_languages = array('en', 'fr');
$default_language = 'fr';
$_SESSION['lang'] = ( isset($_GET['lang']) && in_array($_GET['lang']) ? $_GET['lang'] : $default_language );
From now on you can $_SESSION['lang'] where needed
You could use:
<?
$params = $_GET;
$params['lang'] = 'EN';
$qs = '?';
foreach($params as $k=>$v)
$qs .= $k.'='.urlencode($v).'&';
$url = substr($_SERVER['PHP_SELF'].$qs, 0, -1);
echo $url; //EN
$params['lang'] = 'FR';
$qs = '?';
foreach($params as $k=>$v)
$qs .= $k.'='.urlencode($v).'&';
$url = substr($_SERVER['PHP_SELF'].$qs, 0, -1);
echo $url; //FR
?>
First, store the language in session or cookie.
Second, build link creation mechanism for your website using the current language setting, do not echo the internal links directly. Important internal links should be created from functions so that they format can be change quickly later.

Redirect User Depending on Language

I have the following code:
<?php
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
"da" => "http://www.mysite.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 will redirect the user to the Danish (da) version of the site, which is the main site, if it's a Danish website client. This is excellent.
But, I want, if the user isn't Danish, but Polish, German, etc. it redirects them to the English version of the site, which is located at the subdomain http://en.mysite.com/
How do I implement that into the existing code? Thanks in advance!
- Frederick Andersen
EDIT
A solution like;
$sites = array(
"da" => "http://www.mysite.com/",
"en" => "http://en.mysite.com/"
);
Doesn't work since it creates a loop error when redirecting - at least in Google Chrome.
EDIT 2
session_start();
if (isset( $_SESSION['redirect']))
{
// do nothing / continue with rest of page
}
else
{
$_SESSION['redirect'] = true;
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
"da" => "http://www.mysite.com/",
"en" => "http://en.mysite.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]);
exit();
}
You would need to add the default option to your array:
$sites = array(
"da" => "http://www.mysite.com/",
"en" => "http://en.mysite.com/"
);
Edit: If you are calling this same code in "http://en.mysite.com/" again, it will create a loop. The obvious solution would be to not call this code there, but an alternative solution would be to set a session variable to indicate that the language selection has already taken place.
To add that session variable you could do something like:
session_start();
if (isset( $_SESSION['redirect']))
{
// do nothing / continue with rest of page
}
else
{
$_SESSION['redirect'] = true;
// your language selection code with header call
exit();
}
$sites = array(
"da" => "http://www.mysite.com/",
"en" => "http://en.mysite.com/"
);
how about this
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$sub_domain = ($lang == "da") ? "www" : "en";
$link = "http://".$sub_domain.".mysite.com/";
header('Location: ' . $link);

Categories