The login system I have created logs the user in fine initially, the user is redirected to an index as expected. However when the user clicks on a navigation link to navigate to another page (which is restricted) the user is redirected to the login page. When they login for a second time, every and any page can be accessed properly.
I tried printing out the session id and did a dump of the session array. I noticed when the user goes to the login in page a first they have session id "x", then they are redirected to the index page where they still have the session id "x". However when they try to navigate to another page on the site they are redirected to the login page and have the session id "y". When they login for a second time every pages shows them having session id "y".
What can be causing the session id to be changed after the user is redirected?
Here is my login script.
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$submit = $_POST['submit'];
$error = '';
if(isset($submit)){
// Check if fields are filled out
if($username == '' or $password == ''){
$error = 'Please enter a Username and Password';
}else{ // Proceed with login process
// See if user exists
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
if(mysql_num_rows($query)<1){
echo 'Invalid Username/Password Combination';
}else{ // Grab user's information
$user = mysql_fetch_assoc($query);
if($password == $user['password']){//Login Success, Redirect and set Session Vars
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $user['username'];
$_SESSION['name'] = $user['first'];
$_SESSION['auth'] = $user['authorization'];
session_write_close();
header("Location: home.php");
exit;
}else{
$error = 'Invalid Username/Password Combination';
}
}
}
}
and the page restriction script:
session_start();
if(isset($_SESSION["loggedIn"])){
echo '<div align="right" id="user">Welcome '.trim($_SESSION['name']).'! <a href="../resources/php/logout.php">Sign Out</a> | <a href="../resources/php/editAccount.php">Edit Account</a></div>';
}else{
header("Location: login.php");
}