Skip to Content
Course content

49: Building a Simple Authentication System

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I remember a junior dev I worked with a few years ago who built a small internal tool for their team. They used md5() for passwords because "that's what the old tutorial said." During a routine security review, I pulled up a public rainbow table and cracked three of their team's passwords in about four seconds. The look on their face was a mix of horror and enlightenment. It was a visceral lesson: in the world of authentication, "almost secure" is actually just "broken."

Building an authentication system isn't about inventing a new way to lock a door; it's about using the industry-standard locks that PHP has already provided for us. The core flow is always the same: you verify who the user is (authentication), and then you remember who they are as they move from page to page (session management).

Hashing Passwords the Right Way

First, let's get one thing straight: you never, ever store a password in plain text. You don't even store it using a simple hash like MD5 or SHA1. Instead, we use password_hash(). This function handles the "salting" for you automatically, meaning that if two users have the same password, their stored hashes will still look completely different. This stops attackers from using pre-computed tables to guess passwords.

// When the user registers:
$password = $_POST['password'];
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

// Store $hashedPassword in your database...

When the user tries to log in, you don't "decrypt" the password—because you can't. Instead, you retrieve the hash from the database and use password_verify() to check if the password they just typed matches that hash.

// When the user logs in:
$userInput = $_POST['password'];
$dbHash = $user['password_hash']; // Retrieved from database

if (password_verify($userInput, $dbHash)) {
    echo "Password is valid!";
} else {
    echo "Invalid password.";
}

Maintaining State with Sessions

HTTP is stateless, which is a fancy way of saying the server forgets who you are the millisecond it finishes sending a page. To solve this, we use sessions. Think of a session as a temporary locker on the server; the user gets a key (the session ID stored in a cookie), and they use that key to access their locker on every request.

You must call session_start() at the very top of any file where you need to access session data. Once verified, you can drop the user's ID into the $_SESSION superglobal. I usually stick to storing only the user ID or a role; avoid storing sensitive data like passwords or email addresses in the session if you can help it.

session_start();

if (password_verify($userInput, $dbHash)) {
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    header("Location: dashboard.php");
    exit;
}

Guarding Protected Pages

Now that we can log a user in, we need a way to keep strangers out of our protected pages. The most efficient way to do this is to create a small logic gate at the top of your restricted files. If the session variable we set during login isn't there, we boot them back to the login page immediately.

I've seen people try to build complex middleware for this, but for a simple system, a few lines of code at the top of the page are perfectly fine. Just make sure you call exit; after your header() redirect. If you don't, the rest of the page will still execute in the background, which is a massive security hole.

session_start();

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

// If the code reaches this point, the user is authenticated.
echo "Welcome to your private dashboard, " . $_SESSION['username'];



📋 Practical Task

Exercise: Building a Secure Project Dashboard Gatekeeper

Your goal is to create a mini-authentication flow consisting of three files: register.php, login.php, and dashboard.php.

  • register.php: Create a form that takes a username and password. Use password_hash() to secure the password and save it to a MySQL database table named users.
  • login.php: Create a form that checks the provided username against the database. Use password_verify() to check the password. If successful, start a session and store the user's ID in $_SESSION['user_id'].
  • dashboard.php: This page should be restricted. Implement a check at the very top of the file that redirects any user who is not logged in back to login.php. If they are logged in, display a "Welcome to your Project Dashboard" message.

Bonus Challenge: Add a logout.php file that uses session_destroy() to clear the session and redirect the user back to the login page.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.