PHP - link for actual language id - php

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.

Related

PHP get previous page url after redirect

I want to have a navigation bar that tells the user where they just came from.
Example: Homepage -> Post
But if they are in their posts manager and click on a post, I want it to say
Posts manager -> Post
I read that $_SERVER['HTTP_REFERER'] is not good enough to get the full url so that's not useful as I want the navigation bar all clickable
Any help is much appreciated!
I believe what you want is called breadcrumbs.
What to use for navigation chain storage is actually up to you. You might use even $_SERVER['HTTP_REFERER'] if you want, but that'd be unreliable as it's client-side. Usual way to store such chain is actual URI or session.
For example, you have such URI: http://www.example.com/post_manager/post
Then you can iterate through explode("/", $_SERVER["REQUEST_URI"]) to get each step.
That's basic explanation to guide you to a right direction. You can google alot of samples and snippets using keyword breadcrumbs.
On the topic of saving last visited location (the way to determine wether abonent came from manager or homepage): you can use session's variables to do that. Here's an example:
This way you can set a variable on your homepage:
<?php
session_start();
$_SESSION['previous_location'] = 'homepage';
?>
And then you just access it from another page:
<?php
$previous_location = $_SESSION['previous_location'];
?>
It's important to set session.save_path in your PHP configuration file or your sessions might get lost.
You could do it on the client side if you use the Javascript document.referrer property. However, a better solution may be to use the global session array.
if (!isset($_SESSION['referrer'])) {
$_SESSION['referrer'] = $current_uri;
} else {
$previous_uri = $_SESSION['referrer'];
$_SESSION['referrer'] = $current_uri;
}
The best solution IMO is to save the location into session, every time the user goes to a 'meaningful' page (that you want to be able to navigate back to via this feature), then simply use this array of, say, last 2 visited pages to pull up all the information. Simple and effective.
<?php
session_start();
$_SESSION['user_interactions'][] = $_SERVER['HTTP_REFERER'];
// get previous
$previous_page = end($_SESSION['user_interactions']);
// list all user interactions
foreach($_SESSION['user_interactions'] as $key => $value){
echo $value;
if(count($_SESSION['user_interactions'])-1 != $key) echo ">";
}
?>

PHP: A way to manually switch languages?

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

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
}

Help on changing the page language without changing the current page (PHP)

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

Language neutral entry pages

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

Categories