staying on the current page when changing language - php

I'm setting up a language switcher for my website but have an issue with the actual switcher which always brings back to the homepage (index.php). :-s very annoying
I a complete newbie in php and have been following this tutorial to do so on youtube: https://www.youtube.com/watch?v=cgvDMUrQ3vA
I am trying to implement it on a multi pages website. The actual language swap works like a charm and seems to keep the set language throughout the pages but the mechanism for the switch doesn't because it uses a static link to load index.php + new language attribute, bringing the visiter inevitably back to the homepage instead of reloading the current page.
<?php echo $lang['lang-selector-href'] /* set the <a> tag src="index+lang='x'" */ ?>
<?php echo $lang['lang-selector-switch'] /* display language to be set */ ?>
</a>
i'm using 2 similar files (en.php and fr.php) containing an array to store the translated content
en.php :
<?php
$lang = array(
"lang-selector-href" => "<a href='index.php?lang=fr'>",
"lang-selector-switch" => "Français (French)",
...
...
);
?>
fr.php :
<?php
$lang = array(
"lang-selector-href" => "<a href='index.php?lang=en'>",
"lang-selector-switch" => "English (anglais)",
...
...
);
?>
Question:
How could i could I change the link to:
<a href='current-page.php?lang=fr'> Français (French) </a>
or:
<a href='current-page.php?lang=en'> English </a>
according to the set language?
here is my config.php file
<?php
session_start();
// if no language selected go for english
if (!isset($_SESSION['lang']))
$_SESSION['lang'] = "en";
else if (isset($_GET['lang']) && $_SESSION['lang'] != $_GET['lang'] && !empty($_GET['lang'])) {
if ($_GET['lang'] == "en")
$_SESSION['lang'] = "en";
else if ($_GET['lang'] == "fr")
$_SESSION['lang'] = "fr";
}
// load content
require_once "content/languages/" . $_SESSION['lang'] . ".php";
?>
Sorry if it sounds very basic, i'm sure it is but couldn't find a simple answer that would work...
Thank you!

Make Dropdown list in html which options have language value like below as,
<select onchange="callSomeFunc()">
<option value="fr">French</option>
<option value="en">English</option>
</select>
On change of dropdown list you need to call function which will set selected language value in to php $_SESSION.

Related

How to remove or hide ?lang= from url if select other languages

I have a language selector script. The codes looks like these:
index.php
<?php
session_start();
$allowed_lang = array('en','de');
if (isset($_GET['lang']) === true && in_array($_GET['lang'], $allowed_lang) === true) {
$_SESSION['lang'] = $_GET['lang'];
} else if (isset($_SESSION['lang']) === false) {
$_SESSION['lang'] = 'en';
}
include ''. $_SESSION['lang'] .'.php';
echo $lang['hello'] , '!';
?>
<ul>
<li>English</li>
<li>Deutsch</li>
</ul>
en.php
<?php
$lang = array(
'hello' => 'Hello',
);
?>
de.php
<?php
$lang = array(
'hello' => 'Hallo',
);
?>
The default language is english of course, and if I select another language (e.g German), then after the language change the url is index.php?lang=de. After switching to English the url is index.php?lang=en.
How can I remove or hide ?lang=en or ?lang=de from the url, so if I click the "deutsch" link, tthe language will switch but not append anything to the current URL (e.g index.php)?
Thank you in advance for your answers!
Instead of using GET parameters for the language selection, you could use POST parameters. So you'd have to make the language selector a form which calls the document itself (i.e. without an action attribute, but with method="post") and send and receive the language selection as a POST variable, i.e. not visible.
After that (i.e. for the following pages the user switches to) you could use session variables, cookies or local storage to save and call the selected language.

$_SESSION based language selection is not working properly

My website has two languages: English and Russian. These languages' database names are EN and RU.
I use an old php+smarty script. This script's default language selection codes like this:
if(!isset($_SESSION)){
define('LANGUAGE_ID', 'EN');
} else if ($_SESSION['language'] == '')
{
define('LANGUAGE_ID', 'EN');
}
When I want to see a page in Russian, I visit any page with language phrase (?language=RU) like this:
http://www.example.com/index.php?language=RU
But these pages doesn't load in Russian firstly. When I clicked another link or refresh the page, then page loading in Russian. After saved the cookies, then I can see the pages in Russian when first visit. But If I delete the cookies in browser, then I couldn't see in Russian when first visit.
I tried lots of combinations but I couldn't find any solution. Do you have any idea?
Thank you very much...
Edit:
I found some codes in main.class.php:
function __construct($dbh,$smartyBuild) {
$this->dbh = $dbh;
$this->sitevar = #$smartyBuild->FetchSiteVar();
$this->smartybuild = #$smartyBuild;
if($_REQUEST['language'] !='')
{
$_SESSION['language'] = $_REQUEST['language'];
}
else
{
$langaugeAlready = mysql_fetch_array(mysql_query("select value from ".TABLE_PREFIX."sitevars where array_key = 'default_language_feed'"));
if($_SESSION['language'] == '')
{
$_SESSION['language'] = $langaugeAlready['value'];
}
}
if($_SESSION['language'] !='' )
{
define('LANGUAGE_ID', $_SESSION['language']);
}
else
{
define('LANGUAGE_ID', 'EN');
$_SESSION['language'] = 'EN';
}
}
Is the problem related with these codes?
Like I say, without all the code we are guessing a bit at what the problem is but, here goes...
It seems like you're only checking the $_SESSION variable for the language and not the $_GET variable (which gets the language from the URL). Therefore the value only changes after you refresh the page.
Try this. I am assuming your intention is to show English as a default and only Russian if it is defined in the url, but once defined to keep that language until it is put in the URL again.
//start a session. must be called first on all pages you want it to work on
session_start();
//first check if there's a new language coming from the URL
if(isset($_GET['language']))
{
// if we have a new language setting from the URL, check which one and save it in the session.
// we check it is EN or RO before saving into the session since I don't know what you're using it for later. eg part of a DB query which would be a security risk if it is anything other than EN or RO.
if($_GET['language'] == 'EN')
{
$_SESSION['language'] = 'EN';
}
if($_GET['language'] == 'RO')
{
$_SESSION['language'] = 'RO';
}
}
//now check the session variable, which will have been updated above if changed
if(isset($_SESSION['language']))
{
// already have a language saved, so let's use it
define('LANGUAGE_ID', $_SESSION['language']);
}
else
{
// no language from URL and no language saved, so default to english
define('LANGUAGE_ID', 'EN');
}

How to display a message on joomla homepage only?

How can I display a message only on the homepage of joomla?
I am interested in displaying it on site.com and not site.com/index.php/page or anything else then site.com.
I have tested the following:
<?php $app = JFactory::getApplication();
$menu = $app->getMenu();
$lang = JFactory::getLanguage();
if ($menu->getActive() == $menu->getDefault($lang->getTag())) : ?>this is the homepage
<?php endif; ?>
and this
<?php $menu = & JSite::getMenu();
if ($menu->getActive() == $menu->getDefault()) {
echo "this is the homepage";
}
?>
The problem is that I can still see the message "this is the homepage" on pages like http://site.com/index.php/category/id/78-article which clearly isn't the homepage. It seems that whenever there is index.php in the link, the above code thinks it belongs to the homepage.
This has nothing to do with the 'index.php' in the link. Instead it is related to the fact that the link at http://site.com/index.php/category/id/78-article does not have a menu item associated with it. To do exactly what you are wanting, you will probably need to get a little trickier with the code and check to make sure that the actual page's information matches the homepage information:
$jinput = JFactory::getApplication()->input;
$menu = & JSite::getMenu();
$active = $menu->getActive();
$default = $menu->getDefault();
if (
$active == $default &&
$jinput->get('option') == $default->query['option'] &&
$jinput->get('view') == $default->query['view'] &&
$jinput->get('id') == $default->query['id']
) {
echo "This is the homepage";
}
I am checking the default menu items option (which component) and view and id values against those set in the input.
http://site.com/index.php/category/id/78-article This link will set the id to 78 and likely change the view and option from what it is defined as in the menu for the homepage, so the trigger will not occur.
OK, just an idea but try:
if (preg_match('/index\.php$/',$_SERVER['PHP_SELF'])) {
echo "this is the homepage";
}
You should try this.
1. Check the menu in which has been assigned "Home"(This is the homepage) from the administrator section. Copy the link shown over there.
It would be something like
index.php?option=com_somecomponent&view=someview
Now Goto your index.php in template.
Write a condition there
if(JRequest::getVar('option')=='com_something' && JRequest::getVar('view')=='someview'){ //show message }
This should do the trick for you !! But keep in mind. If you change the menu of homepage, this will have to be changed accordingly.

PHP session variables change with file include

This question is based on a previous question I asked but is getting messy with edits as I was not sure where the problem could come from. (Please advise if this question needs to be closed)
I develop with PHP 5.3.3 on development environment + Apache 2 (my code works there)
The production server has PHP 5.2.6 and the same server (same code doesn't work here)
Thanks to Melsi on the other question I managed to narrow down the problem to a few lines of code.
The problem is: In an include file I start a session and check for a variable.
Depending on that session variable I include a language file.
The structure is like this:
-index.php
INCLUDE
-menus.php
-lang_fr.php
-lang_en.php
The files are as follows:
INDEX.PHP
<?php
//SET LANGUAGE
if (isset($_GET['lang']) && $_GET['lang'] == 'fr') {
$_SESSION['lang'] = 'fr';
}
else if (isset($_GET['lang']) && $_GET['lang'] == 'en') {
$_SESSION['lang'] = 'en';
}
else {
$_SESSION['lang'] = 'en';
}
include_once 'include/menus.php';
?>
<html>
<head>
<title>building...</title>
</head>
<body>
<?php
echo($links);
?>
<br><br>
print_r($_SESSION);
<br><br>
<?php
print_r($_SESSION);
?>
</body>
</html>
MENUS.PHP
<?php
session_start();
if(isset($_SESSION['lang']) && $_SESSION['lang'] == 'en') {
include_once('lang_en.php');
}
else if(isset($_SESSION['lang']) && $_SESSION['lang'] == 'fr') {
include_once('lang_fr.php');
}
else {
$_SESSION['lang'] = 'fr';
include_once('lang_fr.php');
}
$links = <<<EOT
English
French
EOT;
?>
LAN_EN and FR.PHP
<?php
$lang['test'] = "Test";
?>
This on my local server works and displays the correct session variables when I click on the links.
On the production server I get:
-First load: Array ( [lang] => fr ) (default, correct)
-Click on English link: Array ( [lang] => Tn )
-Click on the French link: Array ( [lang] => Tr )
If I change in the language file 'Test' to 'Pest', the results above are 'Pn' and 'Pr'
I would like to know if there's something wrong with the code or with the configuration production server (according to their support there is nothing wrong) and if so what could be the problem.
Note: The problem disappears when I remove the includes in menus.php
The problem in your code is that you as setting the Setting variables and in Index.php but Starting the Session in Menu.php file. Kindly change thing to:
Index.php
<?php
ob_start();
session_start();
//SET LANGUAGE
if (isset($_GET['lang']) && $_GET['lang'] == 'fr') {
$_SESSION['lang'] = 'fr';
}
else if (isset($_GET['lang']) && $_GET['lang'] == 'en') {
$_SESSION['lang'] = 'en';
}
else {
$_SESSION['lang'] = 'en';
}
include_once 'include/menus.php';
?>
<html>
<head>
<title>building...</title>
</head>
<body>
<?php
echo($links);
?>
<br><br>
print_r($_SESSION);
<br><br>
<?php
print_r($_SESSION);
?>
</body>
</html>
MENUS.PHP
<?php
if(isset($_SESSION['lang']) && $_SESSION['lang'] == 'en') {
include_once('lang_en.php');
}
else if(isset($_SESSION['lang']) && $_SESSION['lang'] == 'fr') {
include_once('lang_fr.php');
}
else {
$_SESSION['lang'] = 'fr';
include_once('lang_fr.php');
}
$links = <<<EOT
English
French
EOT;
?>
I Think this would resolve your problem
If you look closely to my answearin your previous question the very first thing mentioned (written in bold) was exactly this:
Maybe a session is started from a file that is included and this should not happen!
Vineet is correct and I will expand his right answear a bit more!
When you include the file child.php into the father.php you must think of the code found in child.php as being part of father.php One of the first things you do in a father.php script (like index.php) is a session start. You do not start a session in an included script because this might create some conflict as an other session could have been started already.
And if you have many files, (even worse if some of them are both included or executed directly cause of no single entry point) then how easy is to manage all this?!
You said this:
Thanks but the problem doesn't come from the structure of my site
Well this might not be entirely true! The thing is that writing old school code (no mvc, no single entry point, not really object oriented) has the benefit that has a very easy learning curve. HOWEVER while such code is easy to write the thing is that such code requires more skills to avoid errors!
On the other hand the object oriented aproach has more difficulty to get started cause there are more things to learn (objects, prototypes, interface, relatinships (belong-to, is part of) etc etc ) and requires a different behaviour. HOWEVER you definetely will benefit more!
A last thing! Well a well structred-site makes the session manage a thing of a few lines, writen only once at the very begining and that's it all.
I am glad that you are twoards solving you problem!

How to implement language packs in PHP

I created 3 language packs for my site: English, Spanish and French. I am just having trouble implementing them based on user selection. I have the following drop down menu:
<select onchange='document.location.href=this.options[this.selectedIndex].value;'>
<option>Select</option>
<option value="?lang=eng">US English</option>
<option value="?lang=esp">Español</option>
<option value="?lang=fra">Français</option>
</select>
How can I include the language files based on what the user selects, I just don't know what to put as the condition in the if statement.
Thanks.
As you're bringing in the option via a query string, you can access it with
$lang = $_GET['lang']
At first, save the value that the user selected in the user session. e.g.:
switch($_POST['lang']) {
case 'en': $_SESSION['lang'] = 'English'; break;
case 'sp': $_SESSION['lang'] = 'Spanish'; break;
default: $_SESSION['lang'] = 'English'; break;
}
On every page request, fetch the language files from the relevant language folder according to the value the you saved.
For example, this how will look the files structure:
English
Global.php
Register.php
Spanish
Global.php
Register.php
Then, whenever you need to load a text file, use:
function load_text_file($filename) {
include 'languages/' . $_SESSION['lang'] . '/' . $filename.'php';
return $txt; // $txt should be an array
}
//...
$text = array();
$text += load_text_file('Global');
$text += load_text_file('Register');
For my template, that piece of code is
$_SESSION['language'] = 'english';

Categories