Reputation: 1188
How can I do one login script that uses cookies for login and for example I want to check if the visitor is logged in without querying the database.
For example I want on frontpage to show some menu's only for logged in users .
so I must do if(isLoggedIn()) show the menu . But that's a query everytime the page loads so it's not very good
Any suggestions?
Upvotes: 1
Views: 282
Reputation: 1256
You can do this:
session_start(); // Use $HTTP_SESSION_VARS with PHP 4.0.6 or less if (!isset($_SESSION['loggedIn'])) { $_SESSION['loggedIn'] = true; // Add all the relevant user information data $_SESSION['username'] = $username; $_SESSION['password'] = $password; $_SESSION['etc'] = $etc; }
Then you can request the user data to the $_SESSION global array. E.g.: requesting if the user is loggedIn (Don't forget to call to session_start() first):
function isLoggedIn() { return (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']); }
If you want to log out:
session_destroy();
The timeout can be handled in the php.ini file:
; After this number of seconds, stored data will be seen as 'garbage' and ; cleaned up by the garbage collection process. session.gc_maxlifetime = 1440
Or you can handle ini variables in run time using ini_set:
ini_set('session.gc_maxlifetime', $sessionMaxLifeTime);
Upvotes: 1
Reputation: 5803
PHP's $_SESSION is file-based, so no DB hit if you're using that (though DBs are almost always faster than file lookups, so that may not be all that helpful).
You can use an in-memory cache like memcached.
Or, for a little less security, you could store a second cookie with a time and hash. When you issue it, you concatenate the present time and a secret salt that only your application logic knows, then md5() or sha1() it. Every browse, you just check that the time in the cookie is within the last hour (or whatever time period you configure) and that the hash is valid. It can be spoofed for an hour, and you'll need to check legit sessions some other way, but it might be enough for just menu-based stuff.
Upvotes: 0
Reputation: 5291
Use http://php.net/manual/en/function.setcookie.php instantly after logging in to set a flag, then use $_COOKIES to check for this flag. Alternatively you can set this flag to $_SESSION and then check it there.
Upvotes: 0
Reputation: 20736
you can use sessions in php for this. Add session_start(); to your pages, after login, maybe againstan database set an flag in the session.
// user logged in sucessful
$_SESSION['logged_in'] = true;
Than check on your pages:
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
// display menu item
}
Upvotes: 0
Reputation: 7832
You can the funcion setcookie to create a cookie and use this function to check if the cookie loggedIn
is set and not false. :)
function isLoggedIn() {
return (isset($_COOKIE['loggedIn']) && $_COOKIE['loggedIn']);
}
Upvotes: 0