How to Build a Secure Login System with PHP and MySQL

Building a user login system is a fundamental skill for any web developer. A well‑implemented system protects user data and ensures only authorized access. This tutorial walks you through creating a secure login system using PHP and MySQL, focusing on best practices like password hashing and prepared statements.

Article illustration

1. Set Up Your Database

First, create a MySQL database and a users table. Use a strong column type for passwords – VARCHAR(255) – to store hashed values.

  • Create database: CREATE DATABASE login_system;
  • Create table:
CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) UNIQUE NOT NULL,
  password VARCHAR(255) NOT NULL
);

2. Build the Registration Form (PHP)

Your registration script must hash passwords using password_hash(). Never store plain‑text passwords. Use prepared statements with MySQLi or PDO to prevent SQL injection.

Registration flow:

  • Collect username and password from a form.
  • Validate inputs (e.g., username length, password strength).
  • Hash password: $hashed = password_hash($password, PASSWORD_BCRYPT);
  • Insert into database using a prepared statement.

3. Create the Login Script

The login process verifies credentials against the stored hash. Use password_verify() to check the password.

  • Fetch user by username with a prepared statement.
  • If user found, verify password: password_verify($input_password, $row['password']).
  • On success, start a session and store user data (e.g., $_SESSION['user_id']).

4. Protect Pages and Handle Logout

Add session checks at the top of protected pages. Provide a logout script that destroys the session.

  • Protect page: if (!isset($_SESSION[‘user_id’])) { header(‘Location: login.php’); exit; }
  • Logout: session_destroy(); header('Location: login.php');

Conclusion

You now have a fundamental, secure login system in PHP and MySQL. Expand it with features like email verification or “remember me” cookies. Always keep security best practices, especially prepared statements and password hashing, at the core of your implementation.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *