PHP MySQL Register and Login Logout with Dashbaord page authenticated

PHP MySQL Register and Login Logout with Dashbaord page authenticated

AI Reading

Quick summary of this article

This article explains how to build a basic authentication system using PHP and MySQL. It covers user registration, login, logout, and a protected dashboard page that only logged-in users can access. The system uses password hashing with bcrypt for security and PHP sessions to manage user login state.

  • User passwords are stored securely using the bcrypt hashing algorithm, not as plain text.
  • The dashboard page checks if a user session exists; if not, it redirects visitors to the login page.
  • Registration stores a unique username and hashed password in a MySQL database.
  • Login verifies the entered password against the stored hash and starts a session on success.
  • Logout destroys the session and redirects the user back to the login page.

Authentication systems are a fundamental part of web applications. They ensure that sensitive information is accessed only by authorized users. In this blog, we’ll create a simple PHP-based authentication system with MySQL to handle user registration, login, logout, and an authenticated dashboard page.


Key Features

  1. User Registration: Users can create accounts.
  2. User Login: Existing users can log in.
  3. Session Management: Ensures secure access to the dashboard.
  4. Logout Functionality: Allows users to log out securely.

Prerequisites

  • A local server environment such as XAMPP or WAMP.
  • Basic knowledge of PHP and MySQL.

Step-by-Step Implementation

1. Database Setup

Create a MySQL database and a users table:

CREATE DATABASE auth_demo;

USE auth_demo;

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

2. Registration Page

register.php

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $conn = new mysqli('localhost', 'root', '', 'auth_demo');

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

    $username = $conn->real_escape_string($_POST['username']);
    $password = password_hash($_POST['password'], PASSWORD_BCRYPT);

    $sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";

    if ($conn->query($sql) === TRUE) {
        echo "Registration successful. <a href='login.php'>Login here</a>.";
    } else {
        echo "Error: " . $conn->error;
    }

    $conn->close();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
</head>
<body>
    <form method="POST">
        <label>Username:</label><br>
        <input type="text" name="username" required><br><br>
        <label>Password:</label><br>
        <input type="password" name="password" required><br><br>
        <button type="submit">Register</button>
    </form>
</body>
</html>

 


3. Login Page

login.php

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $conn = new mysqli('localhost', 'root', '', 'auth_demo');

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

    $username = $conn->real_escape_string($_POST['username']);
    $password = $_POST['password'];

    $sql = "SELECT * FROM users WHERE username = '$username'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        if (password_verify($password, $row['password'])) {
            $_SESSION['username'] = $username;
            header("Location: dashboard.php");
            exit;
        } else {
            echo "Invalid password.";
        }
    } else {
        echo "No user found.";
    }

    $conn->close();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <form method="POST">
        <label>Username:</label><br>
        <input type="text" name="username" required><br><br>
        <label>Password:</label><br>
        <input type="password" name="password" required><br><br>
        <button type="submit">Login</button>
    </form>
</body>
</html>

 


4. Dashboard Page

dashboard.php

<?php
session_start();

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

echo "<h1>Welcome, " . $_SESSION['username'] . "!</h1>";
?>
<a href="logout.php">Logout</a>

 


5. Logout Page

logout.php

<?php
session_start();

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

 


Summary

This blog demonstrated a simple PHP and MySQL-based authentication system, including user registration, login, session management, and a secured dashboard. You can extend this system by adding features like email verification, password reset, or role-based access control.

Leave a Reply

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