views:

42

answers:

1

I am having trouble designing a way to maintain a session with a cookie across multiple pages. I am doing something very similar to this tutorial. I check the password and username from a splash page, and if it is correct then I set a cookie and fill it with a hash. After that I transfer the user to a different page. If the username/password was not correct then it just redirects back to the splash page.

The main problem I cannot figure out is how to check for the validity of the cookie across multiple pages. As the tutorial suggests, I am doing this in PHP. I suppose posting the hash to the new page is not correct, but I cannot think of any other way to check for the validity of the session/user before loading the page.

Thanks in advance.

+4  A: 

That tutorial teaches you to do things in a highly insecure manner. It is incredibly bad to store authentication data of that sort in cookies, especially using such highly obvious names as "username" and "password".

A better (and incredibly more secure than what the "tutorial" teaches) is to use regular PHP sessions. PHP will take care of setting the session cookie for you, and all you do is store your authentication data in the session. At no time will that data ever be sent to the user unless you do it yourself. The only thing that goes back and forth is the session cookie, which is a string of random garbage that "uniquely" identifies the user to PHP.

Once you've got that part done, then you put a small snippet at the top of all your login-required pages, that looks something like this:

<?php

session_start()
if ($_SESSION['loggedin'] !== TRUE) {
   header("Location: http://example.com/login.php");
   echo 'You must log in first';
   exit();
}
?>
<h1>Welcome back, <?php echo $_SESSION['username'] ?></h1>

Unless you're running on a badly misconfigured PHP, or a PHP version from back in the stone ages, there's no way for the remote user to somehow set the 'loggedin' flag without going through your code first.

Marc B
Nothing wrong with using cookies, as long as you md5 the password with a salt before you store it. But you're right, the tutorial is terrible and no one should be storing clear text passwords anywhere (database included).
Noodles
So after I validate the password and username, then I start a session and load the new page. And upon loading the new page I check if the session is loggedin?
Aya
@aya: yes, that's the basics. You can start a session regardless of how the login went, and store a count of login attempts (easy to bypass by deleting the cookie, but could stop less smart people in their tracks). Only if the login is successful do you store the 'loggedin' flag.
Marc B