← All articles
How to Build a Login System in PHP with Secure Password Hashing
PHP and MySQL

How to Build a Login System in PHP with Secure Password Hashing

By John Simiyu · 24 November 2026 · 2 min read

Heading: Why password hashing matters

Almost every business website or web system needs a login page. It might be an admin dashboard, a client portal or a staff system. The way you store passwords decides whether a small mistake becomes a disaster.

I have seen systems where passwords were stored exactly as users typed them. If someone gets access to that database, through a backup leak or a hosting mistake, every account is exposed. Many people reuse passwords on email and mobile banking, so the damage spreads far beyond your website.

The solution is hashing. A hash is a one-way scrambled version of the password. You never store the password itself, only the hash. In this guide I will show you how to build a complete login system in PHP and MySQL the right way.

Heading: What you need

  • PHP 7.4 or newer (PHP 8 is better)
  • A MySQL database, which you can manage from phpMyAdmin in cPanel
  • A text editor and a hosting account or local server

Heading: Step 1: Create the users table

Open phpMyAdmin, select your database, go to the SQL tab and run this:

PHP
your code here
`
```php
``
CREATE TABLE users (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  full_name VARCHAR(100) NOT NULL,
  email VARCHAR(150) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Notice that the column is called password_hash and is 255 characters long. Hashes are long, and PHP may use longer algorithms in future, so always leave room. The UNIQUE on email stops two accounts from sharing the same address.

Heading: Step 2: Connect to the database with PDO

Create a file called db.php:

<?php
$host = 'localhost';
$dbname = 'your_database';
$user = 'your_db_user';
$pass = 'your_db_password';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    exit('Database connection failed.');
}

I use PDO because it supports prepared statements, which protect you from SQL injection. Notice that the error message shown to visitors is generic. Never print real database errors on a live site.

Heading: Step 3: Register users with password_hash()

Create register.php:

<?php
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name  = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($password) < 8) {
        exit('Enter a valid email and a password of at least 8 characters.');
    }

    $hash = password_hash($password, PASSWORD_DEFAULT);

    $stmt = $pdo->prepare('INSERT INTO users (full_name, email, password_hash) VALUES (?, ?, ?)');

    try {
        $stmt->execute([$name, $email, $hash]);
        echo 'Account created. You can now log in.';
    } catch (PDOException $e) {
        echo 'That email is already registered.';
    }
}
?>
<form method="post">
  <input type="text" name="full_name" placeholder="Full name" required>
  <input type="email" name="email" placeholder="Email" required>
  <input type="password" name="password" placeholder="Password" required>
  <button type="submit">Register</button>
</form>

The important line is password_hash($password, PASSWORD_DEFAULT). PHP picks a strong algorithm for you and adds a random salt automatically. You do not need to write your own encryption, and you should never use md5() or sha1() for passwords. They are fast, which makes them easy to crack.

Heading: Step 4: Log in with password_verify()

Create login.php:

<?php
session_start();
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    $stmt = $pdo->prepare('SELECT id, full_name, password_hash FROM users WHERE email = ?');
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($password, $user['password_hash'])) {
        session_regenerate_id(true);
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['full_name'];
        header('Location: dashboard.php');
        exit;
    } else {
        echo 'Invalid email or password.';
    }
}
?>
<form method="post">
  <input type="email" name="email" placeholder="Email" required>
  <input type="password" name="password" placeholder="Password" required>
  <button type="submit">Log in</button>
</form>

A few details here are deliberate:

- password_verify() compares the typed password with the stored hash. You cannot "decrypt" the hash, and you do not need to.
- session_regenerate_id(true) creates a fresh session after login, which helps prevent session fixation attacks.
- The error message is the same whether the email or the password was wrong. This stops attackers from discovering which emails are registered.

Heading: Step 5: Protect pages and add logout

At the top of every private page, such as dashboard.php, add:

<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
?>
<h1>Welcome, <?php echo htmlspecialchars($_SESSION['user_name']); ?></h1>
<a href="logout.php">Log out</a>

And logout.php:

<?php
session_start();
$_SESSION = [];
session_destroy();
header('Location: login.php');
PHP
your code here

code

PHP
your code here

exit;

Always wrap user data in htmlspecialchars() when displaying it. This prevents cross-site scripting (XSS).

Heading: Extra steps that make your system stronger

  • Use HTTPS. Install an SSL certificate so passwords are not sent as plain text over the internet.
  • Limit login attempts. Lock an account or add a delay after several failed tries to slow down guessing attacks.
  • Add CSRF tokens to your forms so other websites cannot submit them on your user's behalf.
  • Rehash when needed. Use password_needs_rehash() at login to upgrade old hashes automatically as PHP improves.
  • Never email passwords. Send a reset link instead.

Heading: Common mistakes to avoid

  • Storing passwords in plain text or with md5()
  • Building SQL queries by joining user input into strings
  • Showing detailed database errors to visitors
  • Using a VARCHAR column that is too short for the hash
  • Forgetting session_start() at the top of the page

Heading: Bonus points before you go

  • Bonus 1: Open your current website's login page right now. If you can see your password in a database backup, it is not hashed, and that is a risk worth fixing today.
  • Bonus 2: Ask whoever built your system one question: "Which algorithm do you use to store passwords?" If the answer is md5, sha1 or "plain text", your users are exposed.
  • Bonus 3: A secure login takes hours to build properly, but a data breach can cost you customers, trust and money. Prevention is always cheaper.
  • Bonus 4: Even a small business with 50 customers is a target. Hackers use automated tools that scan thousands of sites without caring how big they are.

Heading: Final thoughts

A secure login system is not complicated. With PDO, password_hash() and password_verify(), you have the foundation that professional systems are built on. Test it on a local setup or a test subdomain first, then add the extra protections one by one.

If you want a secure login system, admin dashboard or full business system built for your company, I would be glad to help. Reach me on WhatsApp at 0739334082 or email consult@johnsimiyuweb.site.

Next, read: 5 Common PHP Security Mistakes That Get Websites Hacked

Heading: About the author

John Simiyu is an experienced full-time full-stack software developer with proven, robust skills in web development using PHP, Bootstrap, JavaScript, HTML, MySQL and CSS, Python for automation, and Kotlin and Java for native Android development. He has over 5 years of experience building websites, business systems and mobile apps for clients.

Want to learn PHP & MySQL live with me? Book the training →

Comments (0)

No comments yet. Be the first to share your thoughts.

Leave a comment

Comments are reviewed before they appear. Links are not allowed.

Keep reading