Here are the code of my login page where the login script checks for the authenticity of the user and then redirects to inbox page using header function.
<?php
session_start();
include_once('config.php');
$user=htmlentities(stripslashes($_POST['username']));
$password=htmlentities(stripslashes($_POST['password']));
// Some query processing on database
if(($id_user_fetched<=$id_max_fetched) && ($id_user_fetched!=0)){
$_SESSION['loggedIn'] = 'yes';
header("Location:http://xyz/inbox.php?u=$id_user_fetched");
//echo 'Login Successful';
}else{
echo 'Invalid Login';
echo'<br /> <a href="index.html">Click here to try again</a>';
}
}else{
echo mysqli_error("Login Credentials Incorrect!");
}
?>
The inbox.php page looks like this:
<?php
session_start();
echo 'SESSION ='.$_SESSION['loggedIn'];
if($_SESSION['loggedIn'] != 'yes'){
echo $message = 'you must log in to see this page.';
//header('location:login.php');
}
//REST OF THE CODE
?>
Now with the above code, the inbox.php always shows the output: SESSION=you must log in to see this page. Which means that either the session variable is not being setup or the inbox.php is unable to retrieve the session variable. Where am i going wrong?
- Make sure
session_start();
is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening<?php
tag before anything else. Also ensure there are no whitespaces/tabs before the opening<?php
tag.- After the
header
redirect, end the current script usingexit();
(Others have also suggestedsession_write_close();
andsession_regenerate_id(true)
, you can try those as well, but I'd useexit();
).- Make sure cookies are enabled in the browser you are using to test it on.
- Ensure
register_globals
is off, you can check this on thephp.ini
file and also usingphpinfo()
. Refer to this as to how to turn it off.- Make sure you didn't delete or empty the session.
- Make sure the key in your
$_SESSION
superglobal array is not overwritten anywhere.- Make sure you redirect to the same domain. So redirecting from a
www.yourdomain.com
toyourdomain.com
doesn't carry the session forward.- Make sure your file extension is
.php
(it happens!).