Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I have a site that uses cookies to track whether the user is logged in. I set the cookie to expire in X (actual number doesn't matter) seconds.
What I would like to happen is that if the user remains logged in past the expiration time, the code will direct them to the login page.
What happens is that they can close the browser as many times as they want before the expiration time and when they come to the site before the expire time, they are recognized as logged in. Fine.
But as long as they don't close the browser, they are recognized as logged in long past the expire time.
Every time they change pages, I do a "isset($_COOKIE("cookname"))". I expect that this should return false if the cookie has expired. But as long as the browser is not closed, it always returns true.
If they close the browser and come back after the expire time, they are recognized as not logged in, so it appears that I am setting the expire time correctly.
Am I misunderstanding how this should work?

I've never heard of a site that logs you out while you're using the site, but it is definitely possible. In addition to using an expiration on the cookie I would suggest using a timestamp as the value of the cookie. Then in addition to testing if the cookie exists, you could also test if the value of the cookie is X number of seconds before the current time.
Here is a sample working script:
<?php
if (!empty($_COOKIE['login'])) {
$timesincelogin = (time() - $_COOKIE['login']);
if ($timesincelogin > 10) {
setcookie('login', '', time());
$response = "Login time has passed 10 seconds and cookie has been unset";
} else {
$response = "Cookie is set and login is curent.
Will expitre in ".(10-$timesincelogin)." seconds.";
}} else {
$response = "Cookie is NOT set.";
if ($_GET['setcookie']=='true') {
$logintime = time();
setcookie("login", $logintime);
$response .= "
It has been set and will expire in 10 seconds.";
}
}?>
<html><head></head><body><?php echo $response; ?>
</body></html>
Michael J

Thanks. That makes sense.
I wasn't really thinking about logging them out while they use the site, but was thinking about logging them out if they don't use the site for X amount of time.
I could adapt your idea to that tho, but it probably isn't worth it in this case.

![]() |
lamp web hosting
|
What's wrong with Google
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |