I'm trying to convey the session variable $_SESSION['username']
throughout multiple pages for use with queries or just for data check.
The issue I'm having, is that after I log into an account I can use $SESSION['username'] once, but then is lost after I either refresh or move onto a different page. I want to consistently be able to use the session variable throughout the site on multiple pages. It echoes that a user is logged in as "1", and displays $SESSION['username'] only once directly after login, however after refreshing or clicking to another page it doesn't display username anymore, and gives the output "Logged in as" with the username session variable missing.
db_connect.php is a required include at the top of every page where I'd like to maintain my session(below)
<?php
/* check login script, included in db_connect.php. */
session_start();
if(!isset($_SESSION['username']) | !isset($_SESSION['password'])) {
$logged_in = 0;
return;
}
else {
// remember, $_SESSION['password'] will be encrypted.
if(!get_magic_quotes_gpc()) {
$_SESSION['username'] = addslashes($_SESSION['username']);
}
// addslashes to session username before using in a query.
$pass = $db_object->query("SELECT password FROM users WHERE username = '".$_SESSION['username']."'");
if(DB::isError($pass)) {
$logged_in = 0;
unset($_SESSION['username']);
unset($_SESSION['password']); // kill incorrect session variables.
}
$db_pass = $pass->fetchRow();
// now we have encrypted pass from DB in $db_pass['password'], stripslashes() just incase:
$db_pass['password'] = stripslashes($db_pass['password']);
$_SESSION['password'] = stripslashes($_SESSION['password']);
//compare:
if($_SESSION['password'] == $db_pass['password']) { // valid password for username
$logged_in = 1; // they have correct info in session variables.
}
else {
$logged_in = 0;
unset($_SESSION['username']);
unset($_SESSION['password']); // kill incorrect session variables.
}
}
// clean up
unset($db_pass['password']);
$_SESSION['username'] = stripslashes($_SESSION['username']);
?>
The portion of code that sets the session variables for the first time in my login script looks like this:
require('db_connect.php');
$date = date('m d, Y');
$update_login = $db_object->query("UPDATE users SET last_login = '$date' WHERE username = '".$_POST['username']."'");
$_POST['username'] = stripslashes($_POST['username']);
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$db_object->disconnect();
I'm checking session data on other pages by using the following code:
<?php
require('db_connect.php');
if($logged_in == 1) {
echo 'Logged in as '.$_SESSION['username'].', <a href="logout.php">logout</a>';
}
else {
echo 'Not logged in. <a href="login.php">Login</a>';
}
?>