multilanguage site with sub folder - php

Please help me with php file that must redirect to correct language.
the site architecture is
site.com/en
site.com/fr
my cod:
<?php
$sites = array(
"en" => "/en/index",
);
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if (!in_array($lang, array_keys($sites))){
$lang = 'en';
}
// перенаправление на субдомен
header('Location: ' . $sites[$lang]);
?>

You could to append the $_SERVER['PHP_SELF'] variable, that contains the path relative to the document root, to your language folder.
If your path were site.com/fr/file, this variable would contain /fr/file. When you remove the first part of this part, you get the 'language-independent' path of the called script, that you can append to the desired language directory.
If your path is as you described, you could try the following solution (untested!):
<?php
$sites = array(
"en" => "/en",
);
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if (!in_array($lang, array_keys($sites))){
$lang = 'en';
}
$path_to_script = substr($_SERVER['PHP_SELF'], 3);
header('Location: ' . $sites[$lang] . $path_to_script);
?>
EDIT: to clarify the approach:
If the site is site.com/fr/123/index.php, the variable $path_to_script will then contain /123/index.php, the script directory without the leading language dir.
You can then append this to the desired language dir and get the path you wanted: /en/123/index.php

/en/index should be /en/index.php except if you are using Apache's mod_rewrite (not by default). Please provide more details of what is not working so we can help you more.
EDIT:
Furthermore, you could give the user the option of choosing language as 'HTTP_ACCEPT_LANGUAGE' might not be set. In that case, the only choice would be English, which would limit your public.
Some people even recommend about geolocalization, but I find it good enough to add a little drop down menu with languages.

Related

Universal Navigation Bar PHP (Multiple Directories)

So I've been using StackOverflow for programming related topics for over 5 years and never once considered registering as 9/10 times I come on, I find what I am looking for. This time, I've trawled the internet, the suggestions from stack overflow, and I can't find the answer, so here I am.
I'm looking to #include a navigation bar to make it universally accessible no matter what page the user is on. The problem is, I have multiple directories, /login
/register
/profile
The list goes on, of course for things such as CSS files, navigation and JS files. I don't want to constantly have to define the href to be '../' or '../../' of a file. That is an insane amount of maintenance for what soon will be a vast directory of PHP files.
The problem I'm having is trying to calculate how I can detect which directory the user is in via the #include file, and if they wish to return home for example, ensuring the correct amount of change directories occur.
I hope I'm making sense here.
I believe I may require the use of $_SERVER but I'm genuinely stuck on even providing code I've attempted to work on. I'm not expecting a hand out, but more an explanation.
Thanks
This is my first attempt, it works to a degree but it's dependent on the page I originally tested the code on. The echo's is simply to see what is going on myself in the background.
This is incredibly easy to perfect using the Laravel framework but doing it normally for some reason I've struggled with it.
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'index.php';
$folder = $uri;
$folder = "/Folder1/Folder2/Folder3/Folder4/Folder5";
echo substr_count($folder, "/");
echo '<br>' . $folder . '<br>';
$EndLoop = substr_count($folder, "/");
$String = '';
for($Loop = 1; $Loop < $EndLoop; $Loop ++)
{
echo $Loop;
$String = '../' . $String;
echo '<br>';
echo $String;
}
EDIT 2:
I've just worked this which typically works.. I realized when using a
Sign Up
Was routing it to host/directory_currently_in/signup/
So what I have done is this
<?php $host = $_SERVER['HTTP_HOST'];
//further down
echo 'Sign Up';
Because the signup directory is in the root directory and the individual may be 3 directories further in than the root, I had to try find a way to root them right back up 2 or 3 folders back into the sign up directory.
Using http:// and linking to the host has done this for me. Any suggestions on improvements?
Try something along the lines of:
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/common/header.php";
include_once($path);
?>
That way you are always referring to the base and then building the folder structure from there.

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

Auto detect language and redirect user

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
}

Automatic Redirect Depending on Users Language

OBJECTIVE
I'm trying to accomplish an automatic redirect depending on the users language. I have a fully working code for that:
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
"da" => "http://www.fredrixdesign.com/",
"en" => "http://en.fredrixdesign.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 redirects the user to a Danish (da) version, which is the main/root website, if the user is Danish. If the user is German, English, Polish, etc. it redirects the user to a subdomain; en.fredrixdesign.com, which is an English version of the website.
But the problem occurs, when a Danish-user goes on my site. The code, located in the top of my header.php, keep getting executed, which means, it keeps creating the redirect, which finally forces the browser to create an error due to too many redirects. This makes sence.
QUESTION
My question is then; how would I go around modifying the above code, so it only executes the redirect once? If it just completed the redirect, it will simply continue to execute the site.
Well, I bet you can find a solution yourself if just think it over a bit.
All you need is to check if current domain meets desired language.
Just amend your array a bit
$sites = array(
"da" => "www.fredrixdesign.com",
"en" => "en.fredrixdesign.com"
);
and then add a condition for the redirect
if ($sites[$lang] != $_SERVER['HTTP_HOST']) {
header('Location: http://' . $sites[$lang] . '/');
exit;
}
that's all
You could set a cookie value, that tells you that you have already automatically redirected the user to a language-specific site. If that cookie exists, do not do the redirect again. You may also wish to consider the case where the user has cookies disabled.
You could do this with GeoIP + .htaccess, it's really easy to implement.
http://www.maxmind.com/app/mod_geoip
Something like this could do the trick (of course there are tons of heavy good solution but for two languages there is no harm to do simple things and improve later when needed):
function redirectIfUserIsNotOnTheGoodURLBasedOnHisLanguage()
{
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
"da" => "http://www.fredrixdesign.com/",
"en" => "http://en.fredrixdesign.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';
if (($lang == 'da' && $_SERVER['SERVER_NAME'] == 'www.fredrixdesign.com') || // Danish people are on the right place
($lang == 'en' && $_SERVER['SERVER_NAME'] == 'en.fredrixdesign.com')) // Other people are on the right place
{
// no redirection
return;
}
// else redirect to desired location
header('Location: ' . $sites[$lang]);
exit(0);
}
redirectIfUserIsNotOnTheGoodURLBasedOnHisLanguage();

PHP changing language version

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........

Categories