PHP session variables change with file include - php

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!

Related

staying on the current page when changing language

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.

Combine php cookie check with request uri

I'm looking for a way to combine this working script with another check: request uri ?=en or ?=nl. I need this because a php include according to the active language cookie (nl or en) doesn't change immediately after you press the language button. The buttons bring you to [].php?=en - which in fact just refreshes the page. To see the php include in the correct language, you need to refresh the page one more time. Thats a problem. Can anybody help me?
<?php
if( $_COOKIE['lang'] == "nl"){
include ('statement_nl.php');
}
else{
include ('statement_en.php');
}
?>
EDIT:
After a few hours of puzzling I found a way to make it work:
<?php
if( $_COOKIE['lang'] == "nl"){
include ('statement_nl.php'); }
else if (isset($_GET["lang"]) AND ($_GET["lang"]=="nl")) {
include ('statement_nl.php'); }
else if (isset($_GET["lang"]) AND ($_GET["lang"]=="en")) {
include ('statement_en.php'); }
else{
include ('statement_en.php'); }
?>

PHP Sessions not keeping values

I have a problem with my PHP (version 5.6) session. They are not being kept between pages, or even when I refresh my page.
On top of all my files I have :
<?php
session_start();
(there is no space or anything before).
When the user click on link, it's calling a function to set the website language to English or French. After some verification on the $_GET["lang"] value, I create the session like that :
$_SESSION["lang"] = $_GET["lang"];
If I do
var_dump($_SESSION["lang"]);
the server return string(2) "fr" or string(2) "en" regarding to which language the user select. Until there, everything is working great ;)
Problem is if I refresh the page, or go to another one, and try to return the session value, it's always NULL...
I know i could user other ways to translate the website, but I need the sessions to work for other functionality of my application (login, ...)
Because it was working few days ago, I first supposed it was a changed on the server, so I've contact my server administrator, but they told me they didn't change anything.
I have the PHP error reporting set to E_ALL but no errors are displayed...
If someone could help me with that, it would be great, i'm stuck on this bug since 3 days now ^^.
Thanks !
EDIT :
session_start();
var_dump($_SESSION["lang"]);
if(!isset($_SESSION["lang"]) || $_SESSION["lang"] == null){
$_SESSION["lang"] = "fr";
}
if(isset($_GET["lang"]) && ($_GET["lang"] == "fr" || $_GET["lang"] == "en")){
$_SESSION["lang"] = $_GET["lang"];
}
var_dump($_SESSION["lang"]);
from the limited code you're providing, my guess is that the $_GET argument isn't always set, which would then set the session to null.
try this...
if(isset($_GET["lang"])) {
$_SESSION["lang"] = $_GET["lang"];
} else {
echo 'lang not set';
}
EDIT: OP provided additional code.
This will return 'fr' if no value, or if an acceptable value hasn't been provided in the URL arguments. it's similar to what you have, however, I've wrapped the argument check in parentheses to make it a little tighter and changed the order. Your code was returning 'en' if nothing was provided.
session_start();
if(isset($_GET['lang']) && ($_GET['lang'] == 'fr' || $_GET['lang'] == 'en')) {
if($_GET['lang'] == 'fr') {
$_SESSION['lang'] = 'fr';
}
elseif($_GET['lang'] == 'en') {
$_SESSION['lang'] = 'en';
}
} else {
$_SESSION['lang'] = 'fr';
}
var_dump($_SESSION['lang']);
I found it !
My index.php file was encoded in UTF-8, i changed it to UTF-8 without BOM and it worked !
Really weird bug, I hope it will help someone ;)

Multiple PHP includes based on conditional statement

I want to include 2 files based on the following conditional statement
<?php
if (isset($_SESSION['name']) && $_SESSION['name'] == true) {
include 'file_a.php';
}else{
include 'file_b.php';
}
?>
Is this the correct way?
You can try next code:
if(session_id() == '') {
session_start();
include !empty($_SESSION['name']) ? 'file_a.php' : 'file_b.php';
}
It depends what you mean by 'correct':
If you mean 'is it valid' then yes, your code will work and there are no syntax errors.
If you mean 'can it be prettier', then perhaps it could, but it's personal preference whether you'd want to use ternary operators or not:
$toShow = isset($_SESSION['name']) && $_SESSION['name'] ? "file_a.php" : "file_b.php";
include $toShow;
Again, whether or not this is better or worse than your previous code, is down to your personal opinion.
TL;DR: Yes, your code is correct.

Can you variable from part of page be used on another?

I have a variable declared between a<?php ?> tag. Lower down on the page, i have another <?php ?> where id like to use that variable. But when i echo, the variable, it displays off, when the value of the variable is something totally different.
(Ultimately, id like the have the variable in an external include file)
(I posted a similar question here: If statement from external config file not working )
****UPDATE****
Include file (accountsconfig.php):
<?php
$account = 'on';
?>
On my main script, I have a series of if else (if $account == true, do this, else this), but its always going to the else no matter what the value of $account is (As if it doesnt even get the value of $account). Heres an example of one of my ifelse:
<?php
include('accountsconfig.php');
if ($account == 'on') { ?>
<select name="account_number" >
<option value="one">Account One</option>
</select>
<?php } else { ?>
<h1> <?php echo "$account" ?></h1>
<?php } ?>
This file and the accountsconfig.php are located in the same directory.
A possible reason could be, that there is a = sign missing.
Maybe you misspelled the if ($account == 'off') accidentally with a if ($account = 'off') somewhere. That would explain the off value.
Variables remain consistent throughout pages, and it is also possible to declare them in one file and then use them in another. In your case it is likely something else is happening to the variable such as having it's value altered, before you echo it onto the page.

Categories