/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] a question about session variables

Ok, well, since no one was answering my last post, and I figured it out on my own anyway, I have a question about session variables. Say I set $_SESSION[‘variable’] = “some text”; in one page. If I go to another page that I am using sessions on and go to print $_SESSION[‘variable’];, will it print anything or does the information not carry over between pages, even though it is being stored in a superglobal?

to post a comment
PHP

13 Comments(s)

Copy linkTweet thisAlerts:
@thunder77Jan 24.2007 — as long as you [code=php]session_start();[/code] is will display what was stored from your previous page. without that string it does not know to continue to pass the session.

i believe...
Copy linkTweet thisAlerts:
@polorboyauthorJan 24.2007 — I am doing that, but it seems that the session data is not be passed to the next page, I have this code in the pages that I want to redirect back to the login page is the user is not logged in:

If I do this then I can get to the page I want to get to
[code=php]
<?php
session_start();

//recored pages current directory
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);

// set a max file size for the html upload form
$max_file_size = 209715200; // size in bytes

if(isset($_SESSION['logged']) && $_SESSION['logged'] == 1) {
//Do nothing if session logged is true.
} elseif(isset($_SESSION['logged']) && $_SESSION['logged'] == 0){
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "login.php");
exit();
}
?>

[/code]


but if I have this:
[code=php]
<?php
session_start();

//recored pages current directory
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);

// set a max file size for the html upload form
$max_file_size = 209715200; // size in bytes

if(isset($_SESSION['logged']) && $_SESSION['logged'] == 1) {
//Do nothing if session logged is true.
} else { //removed if statement from here.
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "login.php");
exit();
}
?>

[/code]

I keep getting bounced back to the login page, no matter what.

Here is the code for the login page:
[code=php]
<?php
session_start();

$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);

if(isset($_SESSION['logged']) && $_SESSION['logged'] == 1) {
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "upload.php");
exit();
} else {
$logmsg = "";

if (isset($_POST['login'])) {

$username = isset($_POST['username']) ? trim($_POST['username']) : "";
$password = isset($_POST['password']) ? trim($_POST['password']) : "";

if ($username == "" OR $password == "") {
$logmsg = "You must enter both a user name and a password to login.";
} else {
require_once('mysql_config.php');

$connect = mysql_connect(SQL_HOST,SQL_USER,SQL_PASS) or die('Could not connect to the Database.' .mysql_error());
mysql_select_db(SQL_DB,$connect);

$hashpw = hash("sha512",$password);

$query = "SELECT user_name FROM login_info WHERE user_name = '$username' AND password = '$hashpw' LIMIT 1;";
$result = mysql_query($query) or die(mysql_error());

if (mysql_num_rows($result) == 1) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['logged'] = 1;
//$record = "Session logged: " .$_SESSION['logged'];
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "upload.php");
exit();
} else {
$_SESSION['logged'] = 0;
//$norecord = "Session unlogged: " .$_SESSION['logged'];
$logmsg = "<p><span style='color:#CC0000'><strong>The Username and Password you entered does not exist.</strong></span><br/>";
$logmsg .= "You can contact our <a href='mailto:[email protected]'>Customer Service</a> department if you need help with your account.";
}
}

}
}
?>
[/code]


I am setting $_SESSION['logged'] = 1 if the login is accepted, and $_SESSION['logged'] = 0 if it is not. And I call session_start(); first thing on each page I need to use those on, but they don't seem to be getting to the pages.
Copy linkTweet thisAlerts:
@thunder77Jan 24.2007 — All you really need is:
[code=php]if($_SESSION['logged'] == 1)[/code]

I don't believe there is any reason for the isset statement... if the session variable is not set to 1 by your login script than the session is not validated anyway... i.e. if $_SESSION['logged'] != 1 it's going to the login script anyway, or that's what it should do.
Copy linkTweet thisAlerts:
@polorboyauthorJan 24.2007 — Ok, well that didn't change the way it is behaving and I have been looking at this all day and I can't see anything that would be causing the session data from not being passed on to other pages that have session_start() in them.
Copy linkTweet thisAlerts:
@NightShift58Jan 24.2007 — I read somewhere that setting a session variable right before (or close to) a header() redirect often doesn't give PHP time to properly set the session variable. It appears that once it's set, changing the value is not a problem.

This is not a 100% thing, as it seems that this behavior is not consistent from server to server and script to script. But it's worth a try...

To that end, I restructured your script a little, to ensure that the session variable is set as early as possible before the redirect:[code=php]<?php
session_start();

if(!isset($_SESSION['logged']) OR ($_SESSION['logged'] <> 0 AND $_SESSION['logged'] <> 1)) {
$_SESSION['logged'] = 0;
}

$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// Just as a hint...
$directory_self = dirname($_SERVER['PHP_SELF']) ."/";

if (isset($_SESSION['logged']) && $_SESSION['logged'] == 1) {
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "upload.php");
exit();
}

$logmsg = "";

if (isset($_POST['login'])) {

// Set it as early as possible
$_SESSION['logged'] = 0;

$username = isset($_POST['username']) ? trim($_POST['username']) : "";
$password = isset($_POST['password']) ? trim($_POST['password']) : "";

if ($username == "" OR $password == "") {
$logmsg = "You must enter both a user name and a password to login.";
} else {
require_once('mysql_config.php');
$connect = mysql_connect(SQL_HOST,SQL_USER,SQL_PASS) or die('Could not connect to the Database.' .mysql_error());
mysql_select_db(SQL_DB,$connect);

$hashpw = hash("sha512",$password);

$query = "SELECT user_name FROM login_info WHERE user_name = '$username' AND password = '$hashpw' LIMIT 1;";
$result = mysql_query($query) or die(mysql_error());

if (mysql_num_rows($result) == 1) {
$_SESSION['logged'] = 1;
}

if ($_SESSION['logged'] == 0) :
//$norecord = "Session unlogged: " .$_SESSION['logged'];
$logmsg = "<p><span style='color:#CC0000'><strong>The Username and Password you entered does not exist.</strong></span><br/>";
$logmsg .= "You can contact our <a href='mailto:[email protected]'>Customer Service</a> department if you need help with your account.";
} else {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
//$record = "Session logged: " .$_SESSION['logged'];
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "upload.php");
exit();
}
}
}
?>[/code]
Copy linkTweet thisAlerts:
@polorboyauthorJan 24.2007 — Ok, well, now it goes to the right page, but it is like I never added the session stuff in the first place. I can just get to the page by typing in it's address and it is not redirecting me back to the login page and if I go to the login page after I already logged in it is not redirecting me to the upload page. So, it is like it is negating itself and as if it isn't even there now.
Copy linkTweet thisAlerts:
@polorboyauthorJan 24.2007 — If I try to print on the upload page $_SESSION['logged'], it doesn't print anything, shouldn't it print a 1 if it is logged and a 0 if it is not?
Copy linkTweet thisAlerts:
@NightShift58Jan 24.2007 — That's probably because the session is still set when you go back in to test...

The ideal would be to have a logout page somewhere where you actually destroy the session. Testing after that would make more sense.
Copy linkTweet thisAlerts:
@polorboyauthorJan 25.2007 — Ok, well I tried different ways of logging in and out, and regardless of if I use my orginal code or the one you modified I am still getting the same thing. Only when I have:

[code=php]
if(isset($_SESSION['logged']) && $_SESSION['logged'] == 1) {
//Do nothing if session logged is true.
} elseif(isset($_SESSION['logged']) && $_SESSION['logged'] == 0){
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "login.php");
exit();

}
[/code]


can I get to the upload page but if I go and log out and try to get to the upload page again it still loads, even though I did session_destroy() and tried to get to the page again. If on the upload page I have print $_SESSION['logged'], and login from the login page (using the code above on the upload page), it prints that $_SESSION['logged'] doesn't have a value. It is looking like the value I am setting in the login page is not being passed to the following page.
Copy linkTweet thisAlerts:
@polorboyauthorJan 25.2007 — Ok, I just did some more tests. I put into my login page

[code=php]
$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];
[/code]


and printed $logmsg, and it printed out what was stored in them, which was the correct info. I then logged out and put that into my upload page and logged in again and it didn't print anything. Here is what I put into the upload page:
[code=php]
if(isset($_SESSION['logged']) && $_SESSION['logged'] == 1) {

$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];

} elseif(isset($_SESSION['logged']) && $_SESSION['logged'] == 0) {

$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];
//header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "login.php");
//exit();
}
[/code]


and here is the code for my login page (when I just printed out the session info):
[code=php]
<?php
session_start();

if(!isset($_SESSION['logged']) OR ($_SESSION['logged'] <> 0 AND $_SESSION['logged'] <> 1)) {
$_SESSION['logged'] = 0;
}

$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// Just as a hint...
//$directory_self = dirname($_SERVER['PHP_SELF']) ."/";

if (isset($_SESSION['logged']) && $_SESSION['logged'] == 1) {
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "upload.php");
exit();
} else {

$logmsg = "";

if (isset($_POST['login'])) {

// Set it as early as possible
$_SESSION['logged'] = 0;

$username = isset($_POST['username']) ? trim($_POST['username']) : "";
$password = isset($_POST['password']) ? trim($_POST['password']) : "";

if ($username == "" OR $password == "") {
$logmsg = "You must enter both a user name and a password to login.";
} else {
require_once('mysql_config.php');

$connect = mysql_connect(SQL_HOST,SQL_USER,SQL_PASS) or die('Could not connect to the Database.' .mysql_error());
mysql_select_db(SQL_DB,$connect);

$hashpw = hash("sha512",$password);

$query = "SELECT user_name FROM login_info WHERE user_name = '$username' AND password = '$hashpw' LIMIT 1;";
$result = mysql_query($query) or die(mysql_error());

if (mysql_num_rows($result) == 1) {
$_SESSION['logged'] = 1;
}

if ($_SESSION['logged'] == 0) {
//$norecord = "Session unlogged: " .$_SESSION['logged'];
$logmsg = "<p><span style='color:#CC0000'><strong>The Username and Password you entered does not exist.</strong></span><br/>";
$logmsg .= "You can contact our <a href='mailto:[email protected]'>Customer Service</a> department if you need help with your account.";
} else {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
//$record = "Session logged: " .$_SESSION['logged'];
$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];
//header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "upload.php");
//exit();
}
}
}
}
?>
[/code]


I commented out the second $directory_self you had set because it was stopping my page from loading correctly for some reason. So when I printed the session variable info directly on the login page after entering the correct login info, it displays all the correct stuff. When I move that to my upload page and let me login page redirect me to the upload page after logging in, it show that the session variables I set are empty.
Copy linkTweet thisAlerts:
@NightShift58Jan 25.2007 — One step at a time...[code=php]if(isset($_SESSION['logged']) && $_SESSION['logged'] == 1) {

$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];

} elseif(isset($_SESSION['logged']) && $_SESSION['logged'] == 0) {

$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];
//header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "login.php");
//exit();
}[/code]

[/QUOTE]
Logically, this is the way it should look:[code=php]<?php
if (!isset($_SESSION['logged'])) {
// Session doesn't exist
$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "login.php");
exit();
} elseif ($_SESSION['logged'] == 1) {
// Session exists and user is logged in
$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];
} elseif ($_SESSION['logged'] == 0) {
// Session exists but user isn't logged in
$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "login.php");
exit();
}
?>[/code]
We can shorten it to:[code=php]<?php
if (!isset($_SESSION['logged']) OR $_SESSION['logged'] <> 1) {
// Session doesn't exist OR user isn't logged in
$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "login.php");
exit();
} else {
// Session exists and user is logged in
$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];
}
?>[/code]
What your code is lacking is the case of the user that isn't logged in at all, i.e. no session variable set. You're only testing for a set variable and a value but not doing anything in the absence of this variable.
Copy linkTweet thisAlerts:
@NightShift58Jan 25.2007 — [code=php]<?php
session_start();
// Check on the name of the login form page...

$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);

if (isset($_POST['login'])) {
// Whenever a user logs in through the form, reset to not logged in...
$_SESSION['logged'] = 0;
$_SESSION['username'] = "";
$_SESSION['password'] = "";
} elseif(!isset($_SESSION['logged'])) {
// Ditto if the session isn't set
$_SESSION['logged'] = 0;
$_SESSION['username'] = "";
$_SESSION['password'] = "";
} else {
// Anything else, we don't know, so we log him out
unset($_SESSION['logged']);
unset($_SESSION['username']);
unset($_SESSION['password']);
// Send the user to the login form (check on name!!)
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "login_form.php"); // check on name!!
exit();
}

// User passed the basic test...
if ($_SESSION['logged'] == 1) {
// If not coming from the login form and session already set, take the user to upload.php
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "upload.php");
exit();
}

// If we didn't exit, continue...
$logmsg = "";

if (!isset($_POST['login'])) {
// Send the user to the login form (check on name!!)
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "login_form.php"); // check on name!!
exit();
}

$username = isset($_POST['username']) ? trim($_POST['username']) : "";
$password = isset($_POST['password']) ? trim($_POST['password']) : "";

if ($username == "" OR $password == "") {
$logmsg = "You must enter both a user name and a password to login.";
} else {
require_once('mysql_config.php');

$connect = mysql_connect(SQL_HOST,SQL_USER,SQL_PASS) or die('Could not connect to the Database.' .mysql_error());
mysql_select_db(SQL_DB,$connect);

$hashpw = hash("sha512",$password);

$query = "SELECT user_name FROM login_info WHERE user_name = '$username' AND password = '$hashpw' LIMIT 1;";
$result = mysql_query($query) or die(mysql_error());

if (mysql_num_rows($result) == 1) {
$_SESSION['logged'] = 1;
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
//$record = "Session logged: " .$_SESSION['logged'];
$logmsg = "Session Info: " .$_SESSION['username'];
$logmsg .= "<br/>Session Info: " .$_SESSION['password'];
$logmsg .= "<br/>Session Info: " .$_SESSION['logged'];
header("Location: http://" . $_SERVER['HTTP_HOST'] . $directory_self . "upload.php");
exit();
} else {
unset($_SESSION['logged']);
unset($_SESSION['username']);
unset($_SESSION['password']);
//$norecord = "Session unlogged: " .$_SESSION['logged'];
$logmsg = "<p><span style='color:#CC0000'><strong>The Username and Password you entered does not exist.</strong></span><br/>";
$logmsg .= "You can contact our <a href='mailto:[email protected]'>Customer Service</a> department if you need help with your account.";
}
}
?>[/code]
Copy linkTweet thisAlerts:
@polorboyauthorJan 30.2007 — Just an update, I figured out what was wrong. It was my php.ini file. I had the directory for storing sessions set wrong. I left it at the defaults and for some reason it was at /tmp, not tmp. So, it wasn't storing them anywhere. As soon as I got that right everything started working correctly.
×

Success!

Help @polorboy spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.5,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...