Reputation: 698
Initially I came up with the following to see if a user is already logged in:
<?php
session_start();
if(!isset($_SESSION['sessionid'])) {
header("Location: login_form.php");
} else {
echo "You are logged in";
}
?>
$_SESSION['sessionid']
is set when the user manually logs in.
If the user checks "remember me" I set the session cookie's lifetime to be 10 years:
$lifetime = 24*60*60*365*10; // 10 years
setcookie(session_name(),session_id(),time()+ $lifetime,'/');
So now I need to figure out what to do on the server side.... Initially I was thinking of setting session.gc_maxlifetime to a high value so that the server's session data would live for a long time, but 10 years would be ridiculous. Now I'm thinking I should store the session ID in the user table and query that against the session ID. If there's a match, I'll auto log the user in.
My question is: How do I get the session ID from the client?
My understanding is that it will be available after I call session_start(), but only if the server's session data is still available. If the session has expired (which happens depending on the value of session.gc_maxlifetime) a new session ID will get generated when session_start() is called. This would be problematic as it wouldn't match the last session ID that I stored in the user table.
So the ideas I have to read the session ID, after calling session_start() are:
1) $_SESSION['sessionid']
2) $id = session_id();
3) $_COOKIE["PHPSESSID"];
1 and 2 won't work if the server has destroyed the session data, so I don't think I can use these.
3 might work, but when I tried it (echo $_COOKIE["PHPSESSID"];
) I was surprised because the session ID was appeared twice:
the output was this:
htknitopug4b6bv4ql9050pfg6 //htknitopug4b6bv4ql9050pfg6
I simply expected the output to be htknitopug4b6bv4ql9050pfg6.
Can anyone explain the duplicate entry of the session ID? If this behavior is consistent I could always read the first string into my database table.
Upvotes: 0
Views: 14307
Reputation: 165201
The short answer is that you shouldn't do that. For reasons why, please see this answer.
As far as what to do instead, I would set a signed cookie (that post shows how) with a large random string unique for each user. Then, when loading the session if it is new, check for the cookie. Then look up the user based on that random string. If you find one, silently log the user back in.
This is a pretty standard remember-me function, but it avoids the pitfals of having long-running sessions, or using the session identifier for other things.
One thing to note, you really should be rotating your session identifier pretty often as well. I typically do it for every login/logout event as well as whenever the user does something sensitive (admin forms, posting content, etc). There's nothing wrong with rotating too much...
Upvotes: 2