Page 1 of 1

$_SESSION - how to access session variables on other pages

Posted: Thu Jun 20, 2002 12:43 pm
by verabug
After starting a session, I'm not able to access a session variable with $_SESSION['var_name']. I'm totally new to this so I'm probably doing something wrong. I am using PHP 4.2+ with register_globals off, meaning I don't have to use session_register.

Here is my session starting code:

code:--------------------------------------------------------------------------------
// attempt to authorize user with database
$userID = auth($name, $pass);

if ($userID != -1) {
session_start();
$_SESSION['username'] = $name;
if ($success) {
header('location:eq_authorized.php');
}
} else {
header('location:eq_login.php?message=Ooops! Wrong username and/or password!');
}
--------------------------------------------------------------------------------
Then in eq_authorized.php, I have this code:

code:--------------------------------------------------------------------------------
if (isset($_SESSION['username'])) {
echo("yey!");
} else {
echo("waah");
}
--------------------------------------------------------------------------------
And it's not recognized the 'username' variable. I get no error message, and I'm pretty sure the session is getting started okay because I saw a session file in my Windows\Temp folder. What am I doing wrong

Posted: Thu Jun 20, 2002 1:12 pm
by twigletmac
To see if anything is being set in the $_SESSION array add:

Code: Select all

echo '<pre>';
print_r($_SESSION);
echo '</pre>';
to your code.

Also try putting session_start() at the top of the script outside of the if loop.

Mac

Posted: Thu Jun 20, 2002 1:18 pm
by jason
Remember, if you want to use session variables you have to call session_start() first, whether you are initializing a session, or continuing one.

Posted: Thu Jun 20, 2002 1:21 pm
by verabug
twigletmac,
the code you suggested returned a username on the page that started the session. But on the page where I really need the info, it doesn't return anything. I thought $_SESSION variables were automatically accessible on all pages?

Posted: Thu Jun 20, 2002 1:22 pm
by verabug
Jason,
Are you saying I need to include session_start() in each script where I want to have access to session variables?

Posted: Thu Jun 20, 2002 1:26 pm
by twigletmac
Jason's right, they're only accessible if session_start() is called at the top of the script.

Check the manual:
php.net manual wrote:session_start() creates a session (or resumes the current one based on the session id being passed via a GET variable or a cookie).
Mac

Posted: Thu Jun 20, 2002 1:26 pm
by verabug
Yes, you are, yes, you are! Woohoo, that did it!
Thanks guys.

Posted: Thu Jun 20, 2002 1:55 pm
by jason
No problem. :D :D :D

Code: Select all

<?php
$GLOBALS&#1111;'users']&#1111;'jason']&#1111;'posts']++;
?>