Reputation: 475
I've been trying to search online for possible answers to this question, but I really can't figure it out. There are many people with a similar problem, but mine has a unique touch to it that I don't understand, nor have I encountered it anywhere else.
I created a login system that worked fine. However, I wanted to make it more secure, so I used this tutorial: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL. I can still login, but whenever I refresh my page, I automatically log out. After I while I figured out that the session ID changes.
The curious thing is this, when I call var_dump($_SESSION); on the 3rd line of my code (directly after session_start();), the session ID remains the same, and everything works. As soon as I comment this line, the problem returns.
I do regenerate the session ID using the following code:
$session_name = 'robinator123'; // Set a custom session name
$secure = FALSE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(true); // regenerated the session, delete the old one.
When I call the var_dump($_SESSION);, the regeneration fails because the headers have already been sent by the var_dump. However, when I replace var_dump with a normal echo statement the headers also fail, but the session ID still changes. I have no idea what's going on.
A few notes:
Upvotes: 1
Views: 2344
Reputation: 475
I actually solved the problem by editing the regeneration piece of code. Removing the regeneration didn't work, but I fixed it by setting the parameters I had forgotten to change (i.e. lifetime, path, and domain), and by removing the parameter "true" from the session_regenerate_id(); command (I literally copy-pasted this code from the tutorial, and failed to notice these things when I was making all the changes).
However, I'm still very curious how var_dump was able to avoid the problem..
Upvotes: 1