Building a Simple Login System in PHP: Authentication Basics

This entry is part 6 of 9 in the series February 2025 - Love and Ethics

Authentication is a crucial part of many web applications, ensuring that only authorized users can access specific content or features. In this guide, we’ll walk through how to build a simple login system in PHP, covering the basics of securely handling user data and authentication.

This tutorial assumes a basic understanding of PHP and access to a development environment with PHP and a MySQL database installed.

1. Setting Up the Database

First, create a database and a table to store user credentials. Use the following SQL command to set up a users table:

CREATE DATABASE login_system;

USE login_system;

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

Here:

  • username stores the user’s login name.
  • password stores a hashed version of the user’s password for security.

2. Registration: Adding New Users

Create a PHP script to handle user registration. This involves securely storing the user’s password using hashing to protect it from unauthorized access.

registration.php

<?php
// Database connection
$conn = new mysqli('localhost', 'root', '', 'login_system');

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

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

    // Hash the password
    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);

    // Insert the user into the database
    $sql = "INSERT INTO users (username, password) VALUES (?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ss', $username, $hashedPassword);

    if ($stmt->execute()) {
        echo "User registered successfully!";
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
}

$conn->close();
?>

3. Login: Authenticating Users

Next, create a login script to validate user credentials against the database.

login.php

<?php
// Database connection
$conn = new mysqli('localhost', 'root', '', 'login_system');

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

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

    // Fetch the user from the database
    $sql = "SELECT * FROM users WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();

        // Verify the password
        if (password_verify($password, $user['password'])) {
            echo "Login successful! Welcome, " . htmlspecialchars($username);
        } else {
            echo "Invalid username or password.";
        }
    } else {
        echo "Invalid username or password.";
    }

    $stmt->close();
}

$conn->close();
?>

4. HTML Forms for Registration and Login

registration_form.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Register</title>
</head>
<body>
    <h2>Register</h2>
    <form method="POST" action="registration.php">
        <label for="username">Username:</label>
        <input type="text" name="username" id="username" required><br><br>
        <label for="password">Password:</label>
        <input type="password" name="password" id="password" required><br><br>
        <button type="submit">Register</button>
    </form>
</body>
</html>

login_form.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <form method="POST" action="login.php">
        <label for="username">Username:</label>
        <input type="text" name="username" id="username" required><br><br>
        <label for="password">Password:</label>
        <input type="password" name="password" id="password" required><br><br>
        <button type="submit">Login</button>
    </form>
</body>
</html>

5. Security Best Practices

  • Password Hashing: Always hash passwords using a strong algorithm (e.g., password_hash in PHP). Never store plaintext passwords.
  • SQL Injection Protection: Use prepared statements with parameterized queries to prevent SQL injection.
  • HTTPS: Always serve login forms over HTTPS to encrypt user data during transmission.
  • Session Management: For production systems, implement session management to securely handle user authentication.

Conclusion

Authentication is a crucial part of many web applications, ensuring that only authorized users can access specific content or features. In this guide, we’ll walk through how to build a simple login system in PHP, covering the basics of securely handling user data and authentication.

Series Navigation<< Faith and Love in the Workplace: Showing Christ’s Love DailyHow Christians Can Reflect Integrity in Their Professional Lives >>