views:

78

answers:

5

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?

A: 

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']);
}
TiuTalk
yes but it can easily be modified and hacked by any user. If I'll do that, I can easily set it to true and modify the username to admin, add one random password and I will be logged in as admin :\
FinalDestiny
A: 

Hi,

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
}
ArneRie
yes, I thinked about this, but if I add this, it will expire in 20 minutes. The cookies for username and password will last for 3 hours for example so I will have the username and the password but not the loggedin cookie
FinalDestiny
A: 

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.

Sam Dark
But cookies can be easily modified
FinalDestiny
A: 

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.

Brock Batsell
A: 
feragusper