Log in

View Full Version : Resolved Problem parsing variable



Rohan72
02-21-2010, 12:26 AM
I'm trying to use a script to select a language from a form.

No matter what I select, the language file does not change. when i manually set the language ($lang = 'english' or $lang = 'dutch') then the correct language file is loaded.

Can anyone help me out on this? (just adjusting the code without dismissing my code altogether and suggesting something completely different)



<?php session_start(); ?>

<?php
function check_lang() {
//make sure that we have a language selected by using session ..
if (!isset($_SESSION['lang'])) {
/* you can either show error message and terminate script
die('No language was selected! please go back and choose a langauge!');*/
//or set a default language
$lang = 'english';
} else {
$lang = $_SESSION['lang'];
}

//directory name
$dir = 'languages';

//now we return the langauge wanted !
//Returned String Format: dirname/filename.ext
return "$dir/$lang.lng";
}
?>


<div id="langsel">
<form action="index.php" method="get">
<select name="lang" onchange="this.form.submit();">
<option value="english">English</option>
<option value="dutch">Nederlands</option>
</select>
</form>

</div>

<?PHP
//this function will check user language and return the file name to be included ..
$lang = check_lang();
include_once($lang);
?>

djr33
02-21-2010, 12:36 AM
That script doesn't actually do anything. You are using $_SESSION['lang'] in your PHP and in the html you have a form that will submit as post data.

Using the session is good as well, but in order to set the language the first time, you need to use $_POST['fieldname'] to get the value. For example,

if (isset($_POST['lang'])) {
if (!in_array($_POST['lang'],array('english','dutch',...))) { break; } //security
$_SESSION['lang'] = $_POST['lang'];
}
//continue checking if $_SESSION['lang'] is set below here

Rohan72
02-21-2010, 12:45 AM
Where do i have to insert that bit? Could you add it to my script?
I tried to put it right after the "function check_lang();" line but it didn't do anything.

djr33
02-21-2010, 12:52 AM
As soon after you do session_start() as possible.
Right before this line (but within <?php ....) would probably be best:
function check_lang() {


However, depending on the final format of your page you may want to move things around a bit.

Crucially, this is setting $_SESSION['lang'] based on the submitted data, so it must be BEFORE you use check_lang(). You could put it anywhere before that, though.
In other words, you placed it exactly one line too late.

Rohan72
02-21-2010, 11:56 PM
Thanks a lot!!!!

The script first failed, but then i started to play around with it and it finally worked when I replaced $_POST with $_GET.

djr33
02-22-2010, 09:17 AM
Sorry, yes, your method was set to get. Usually forms submit as post, but in this case get makes sense.
Glad it works!