How to Build a Simple PHP Login System from Scratch – Step-by-Step Guide

How to Build a Simple PHP Login System from Scratch - Step-by-Step Guide
Share

Are you looking to create a secure and functional PHP login system for your website? Whether you’re a beginner or an intermediate developer, building a simple PHP login tutorial from scratch is a great way to understand user authentication, session management, and database integration. In this step-by-step guide, we’ll walk you through the process of creating a PHP login script using PHP and MySQL—no frameworks, just pure, clean code.

By the end of this article, you’ll learn how to:

  • Set up a MySQL database for user credentials
  • Create a user registration form
  • Build a secure login system with PHP
  • Implement session management for user authentication
  • Add basic security to protect against common vulnerabilities

Let’s dive into building your own PHP MySQL login system!

Why Build a PHP Login System from Scratch?

While frameworks like Laravel offer built-in authentication systems, understanding how to build a PHP login system manually gives you full control and a deeper knowledge of how authentication works. Plus, it’s lightweight and perfect for small projects or learning purposes. Keywords like PHP user authentication and secure PHP login are trending as developers seek custom solutions.

Prerequisites

Before we start, ensure you have:

  • A local server (e.g., XAMPP, WAMP, or MAMP) with PHP installed
  • MySQL database access (via phpMyAdmin or similar)
  • Basic knowledge of HTML, CSS, PHP, and MySQL

Step 1: Set Up the Database

First, we need a database to store user information. Open phpMyAdmin (or your preferred MySQL tool) and create a database called login_db. Then, create a users table with the following SQL query:


CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

This table stores a unique ID, username, hashed password, and creation timestamp. The VARCHAR(255) for the password ensures we can store securely hashed passwords.

Step 2: Create the Project Structure

In your local server’s root directory (e.g., htdocs in XAMPP), create a folder called php-login-system. Inside it, add these files:

  • config.php – Database connection
  • register.php – Registration form and logic
  • login.php – Login form and logic
  • dashboard.php – Protected page after login
  • logout.php – Logout script

Step 3: Database Connection (config.php)

Create config.php to connect to your database:


<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'login_db');

$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

if ($conn === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>

Update the credentials if your setup differs (e.g., add a password if required).

Step 4: Build the Registration System (register.php)

Let’s create a registration form. Add this code to register.php:


<?php
require_once "config.php";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);
    $password_hash = password_hash($password, PASSWORD_DEFAULT);

    $sql = "INSERT INTO users (username, password) VALUES (?, ?)";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "ss", $username, $password_hash);

    if (mysqli_stmt_execute($stmt)) {
        echo "Registration successful! <a href='login.php'>Login here</a>";
    } else {
        echo "ERROR: Could not register.";
    }
    mysqli_stmt_close($stmt);
}
mysqli_close($conn);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Register - PHP Login System</title>
</head>
<body>
    <h2>Register</h2>
    <form method="post">
        <label>Username:</label><br>
        <input type="text" name="username" required><br>
        <label>Password:</label><br>
        <input type="password" name="password" required><br>
        <input type="submit" value="Register">
    </form>
</body>
</html>

This script hashes the password using password_hash() for security and inserts the user into the database.

Step 5: Create the Login System (login.php)

Now, let’s build the login page. Add this to login.php:


<?php
session_start();
require_once "config.php";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);

    $sql = "SELECT id, username, password FROM users WHERE username = ?";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "s", $username);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);

    if (mysqli_stmt_num_rows($stmt) == 1) {
        mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
        mysqli_stmt_fetch($stmt);
        if (password_verify($password, $hashed_password)) {
            $_SESSION["loggedin"] = true;
            $_SESSION["id"] = $id;
            $_SESSION["username"] = $username;
            header("location: dashboard.php");
        } else {
            echo "Invalid password.";
        }
    } else {
        echo "Username not found.";
    }
    mysqli_stmt_close($stmt);
}
mysqli_close($conn);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login - PHP Login System</title>
</head>
<body>
    <h2>Login</h2>
    <form method="post">
        <label>Username:</label><br>
        <input type="text" name="username" required><br>
        <label>Password:</label><br>
        <input type="password" name="password" required><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>

This uses password_verify() to check the password and starts a session for authenticated users.

Step 6: Protect the Dashboard (dashboard.php)

Create a protected page that only logged-in users can access:


<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: login.php");
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
</head>
<body>
    <h2>Welcome, <?php echo htmlspecialchars($_SESSION["username"]); ?>!</h2>
    <p>This is your dashboard.</p>
    <a href="logout.php">Logout</a>
</body>
</html>

Step 7: Add Logout Functionality (logout.php)

Finally, create logout.php to end the session:


<?php
session_start();
$_SESSION = array();
session_destroy();
header("location: login.php");
exit;
?>

Step 8: Basic Security Tips

To make your secure PHP login even safer:

  • Use htmlspecialchars() to prevent XSS attacks (as shown in dashboard.php)
  • Validate and sanitize all user inputs
  • Use HTTPS in production to encrypt data
  • Consider adding CSRF tokens for form submissions

Conclusion

You’ve just built a simple PHP login system from scratch! This tutorial covered database setup, registration, login, session management, and basic security. Want to dive deeper into PHP security? Check out this official PHP security guide for more advanced tips.

Now, go ahead and customize your PHP login script—add styling, enhance security, or integrate it into a larger project. Happy coding!

Looking for more PHP tutorials? Explore our PHP category page for additional guides, tips, and tricks to level up your coding skills!

Table of Contents
Scroll to Top