I am using sessions to log users into my site.
The login form sends the input to a login-exec file which then queries the db and validates the login info. I have placed session_start(); at the beginning of the login-exec file and then used the below snippet to write data to the session:
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
$_SESSION['Username'] = $member['username'];
$_SESSION['key'] = $member['Serial'];
session_write_close();
header('Location: account.php');
at the beginning of the account.php file i have required the auth.php to validate the session.
account.php: require_once('auth.php');
auth.php:
<?php
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
header("Refresh: 5; url=login.php");
//echo $_SESSION['SESS_MEMBER_ID'];
die("Access Denied!");
exit();
}
?>
Always the first time logging in it returns access denied. When the script redirects back to the login page and I try again it always works… I have saved my php files in UTF-8 Without BOM as I originally thought there was leading white space before the session was started. That did not fix the issue and I really can’t figure this out.
Any ideas as to why this is happening?
I believe the issue was the redirection url in my login-exec.php script. For example:
If I loaded the login.php script by going to http://www.mydomain.com/mysubdirectory/login.php and the header redirect in login-exec.php was pointing to http://subdomain.mydomain.com/account.php the PHPSESSID was being regenerated because the domain changed.
So I changed the header redirects to account.php instead of the full url and this resolved the issue.
I could have used a full URL either subdomain.mydomain.com or mydomain.com/subdirectory/ but in doing so would of restricted the user and the scripts portability. So simple answer..ensure the domain is staying the same. If it isn’t you can set the session name which I am pretty sure would resolve this aswell. However in my case
header('Location: script.php');did the trick.