views:

27

answers:

1

Hey,

I'm having problems with cookies on my website. After validating user credentials, the following code is executed if "remember me" is set:

session_start();
    $_SESSION['username'] = $myusername;
if(isset($_POST['remember'])){
        setcookie("cookname", $_SESSION['username'], time() + 60 * 60 * 24 * 100, "/");
}

Every page on the site then has the following code at the beginning:

session_start();

if(isset($_COOKIE['cookname']) && !isset($_SESSION['username'])){
    $_SESSION['username'] = $_COOKIE['cookname'];
}

If I close the browser window and then open it again, the website has the login prompt even if "remember me" was set. Oddly, if I close just the tab for the website and then go back to it, it remembers that I logged in. What's going on?

Thanks in advance,

Matt

+4  A: 
  1. Don't store passwords in cookies.
  2. You need to call session_start before storing anything into the session.
  3. In many browsers (e.g. Firefox), you can view the cookies that are actually set. You can also view the HTTP headers in Fiddler or LiveHTTPHeaders. This should help debugging.
Matthew Flaschen
@part 2: ya, i've pasted more code for that part, sorry
Matt
+1 for his first point. Cookies are simple textfiles; anyone can read them.
eykanal
@part 1: should i just have the "cookname" cookie and leave it at that? is this generally the only thing stored in cookies?
Matt
For cookies, store stuff such as first name, last name, anything very basic. NEVER passwords.
ggfan
+1 Passwords shouldn't be stored even in the *session* if it can be avoided.
Pekka
'Aight, I'll try LiveHTTPHeaders. Thanks
Matt
If you're using the "cookname" value for any type of elevated permissions you should also store some kind of checksum so that you can validate that what's being sent back is what you set in the first place.
King Isaac