Login process

First off, if anyone can recommend a good tutorial on creating a login process using cookies and sessions, feel free to help a kid out.

Secondly, I’m trying to figure out what the best approach is with using a cookie-session with a login process. I feel a bit silly trying to make this on my own as I’ve never done it, but hey–now is as good of a time as ever, right?

So to that end, I keep telling myself that I should check for the cookie before outputting any login form and if a cookie is found (with the appropriate data), then it will either let you in or force the auth on ya. After that, the session information would be injected into the cookie…? Is that close?

Anyway, if anyone could shine some general light on the general process, I would be appreciative.

What is the purpose of the cookie for you? Do you intend to keep someone logged in for days/weeks?

Full PHP authentication system.




if (!empty($_POST)) {
  if ($_POST['username'] == 'something' && $_POST['password'] == 'something') {
    $_SESSION['username'] = $_POST['username'];
    header("Location: member.php");

<form action="login.php" method="post">
Username: <input type="text" name="username" value="" /><br />
Password: <input type="password" name="password" value="" /><br />
<input type="submit" value="Log in" />

And at the top of any page you want to require a login for:



if (!isset($_SESSION['username'])) {
  header("Location: login.php");

//rest of the now-protected page

Just fill in the details, like looking up the username/password in a database if you’re using one, and where to redirect upon logging in.

Dan, I really appreciate the code. I think the thing I was a bit foggy on is when and where to include the session stuff. Thanks for clearing that up. What about the cookie implementation? Is that just the simple “setcookie()” stuff or is there more to it than that?

setcookie() creates a cookie, yes, and you can read them from $_COOKIE

I don’t know what you’re wanting to use the cookie to do though?

Sorry Dan, I should’ve explained…

I was thinking that the cookie could be used to keep the person logged-in while also retaining various settings that the person might wish to keep, such as the way a DIV is displayed or whatever.