PHP Implementing a User Authentication System

Implementing a user authentication system in PHP involves managing user accounts, securely storing passwords, and verifying user credentials. Below is a basic example to help you get started with building a simple user authentication system.

Step 1: Database Setup

First, create a table named users in your MySQL database to store user information.

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

Step 2: PHP Scripts

1. Database Connection

Create a file named db.php to establish a database connection.

<?php
$host = 'localhost';
$dbname = 'your_database_name';
$username = 'your_username';
$password = 'your_password';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}
?>

2. Registration Page

Create a file named register.php for user registration.

<?php
require_once 'db.php';

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

    $stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $password);

    if ($stmt->execute()) {
        echo "User registered successfully.";
    } else {
        die("Registration failed.");
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Registration</title>
</head>
<body>
    <h1>User Registration</h1>
    <form action="register.php" method="post">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username" required><br><br>
        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password" required><br><br>
        <input type="submit" value="Register">
    </form>
</body>
</html>

3. Login Page

Create a file named login.php for user login.

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

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

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        header("Location: profile.php");
        exit();
    } else {
        echo "Invalid username or password.";
    }
}
?>

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

4. Profile Page (Authenticated Area)

Create a file named profile.php for the user’s profile page (authenticated area).

<?php
session_start();

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

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

// Fetch user details from the database
// You can display user information or allow actions like logout here
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Profile</title>
</head>
<body>
    <h1>Welcome, <?= htmlspecialchars($username) ?></h1>
    <p>This is your profile page.</p>
    <a href="logout.php">Logout</a>
</body>
</html>

5. Logout Page

Create a file named logout.php for user logout.

<?php
session_start();
session_destroy();
header("Location: login.php");
exit();
?>

Notes

  • Always hash passwords securely using password_hash() function before storing them in the database.
  • Use password_verify() function to verify passwords during login.
  • Protect sensitive pages by checking session variables ($_SESSION) to ensure only authenticated users can access them.
  • Implement additional features such as password reset, email verification, and user roles as per your application requirements.

This example provides a foundational approach to implementing a basic user authentication system in PHP. Further enhancements and security measures can be added based on specific project needs and best practices.

Leave a Reply

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