Share this:

Today we are going to learn Creating a Login and Registration System in PHP 8.1. A login and registration system is an essential component of any web application that requires user authentication. In this blog post, we’ll walk you through the process of creating a simple login and registration system using PHP 8.1 and MySQL as the database.

By the end of this tutorial, you’ll have a basic understanding of how to implement user authentication in your own web applications.

Prerequisites:

  • Basic knowledge of PHP and MySQL
  • PHP 8.1 and MySQL installed on your local development environment
  • A text editor or IDE

Step 1: Setting up the database

First, create a new database and a table to store user information. In this example, we’ll create a table called users with the following fields: id, username, email, and password.

  • Open your MySQL client or phpMyAdmin, and create a new database called login_system.
Create Database
Create Database
  • Run the following SQL query to create the users table:
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Create Users Table
Create Users Table

Step 2: Establishing a database connection

Create a new PHP file called db.php and add the following code to establish a connection to your MySQL database:

<?php

$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "login_system";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
?>
Establishing a database connection
Establishing a database connection

Replace your_username and your_password with your MySQL credentials.

Step 3: Creating the registration form

Create a new file called register.php and add the following HTML and PHP code to create a simple registration form:

<?php
include 'db.php';

if (isset($_POST['register'])) {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    $sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sss", $username, $email, $hashed_password);
    $stmt->execute();

    if ($stmt->affected_rows > 0) {
        header("Location: login.php");
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $stmt->close();
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register</title>
    <!-- Add Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <div class="card my-5" >
                    <div class="card-body">
                        <h1 class="text-center ">Creating a Login and Registration System in PHP 8.1 - LaravelTuts.com</h1>
                    </div>
                </div>

                <h1 class="text-center my-5">Register</h1>
                
                <form action="register.php" method="post">
                    <div class="form-group mb-2">
                        <label for="username" class="mb-2">Username:</label>
                        <input type="text" name="username" id="username" class="form-control" required>
                    </div>
                    <div class="form-group mb-2">
                        <label for="email" class="mb-2">Email:</label>
                        <input type="email" name="email" id="email" class="form-control" required>
                    </div>
                    <div class="form-group mb-3">
                        <label for="password" class="mb-2">Password:</label>
                        <input type="password" name="password" id="password" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <input type="submit" name="register" value="Register" class="btn btn-primary">
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Bootstrap JS and its dependencies -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
</body>
</html>
Creating the registration form
Creating the registration form

The above code includes the Bootstrap CSS and JS files from a CDN, adds Bootstrap classes to the form elements, and wraps the form in a container and row with appropriate column classes for responsive behavior.

Now that the registration form is styled with Bootstrap, let’s proceed with creating the login form.

Step 4: Creating the login form

Create a new file called login.php and add the following HTML and PHP code to create a simple login form styled with Bootstrap:

<?php
include 'db.php';

session_start();

if (isset($_POST['login'])) {
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    $sql = "SELECT * FROM users WHERE email = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_email'] = $user['email'];
        header("Location: dashboard.php");
    } else {
        $error_message = "Invalid email or password";
    }

    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Creating a Login and Registration System in PHP 8.1 - LaravelTuts.com</title>
    <!-- Add Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <div class="card my-5" >
                    <div class="card-body">
                        <h1 class="text-center ">Creating a Login and Registration System in PHP 8.1 - LaravelTuts.com</h1>
                    </div>
                </div>

                <h1 class="text-center my-5">Login</h1>

                <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger" role="alert">
                        <?= $error_message; ?>
                    </div>
                <?php endif; ?>

                <form action="login.php" method="post">
                    <div class="form-group mb-2">
                        <label for="email" class="mb-2">Email:</label>
                        <input type="email" name="email" id="email" class="form-control" required>
                    </div>
                    <div class="form-group mb-3">
                        <label for="password" class="mb-2">Password:</label>
                        <input type="password" name="password" id="password" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <input type="submit" name="login" value="Login" class="btn btn-primary">
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Bootstrap JS and its dependencies -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
</body>
</html>
Creating the login form
Creating the login form

Now that we have the login form, let’s create a simple dashboard for logged-in users.

Step 5: Creating the dashboard

Create a new file called dashboard.php and add the following HTML and PHP code to display a simple dashboard for authenticated users:

<?php
include 'db.php';

session_start();

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

if (isset($_POST['logout'])) {
    session_destroy();
    header("Location: login.php");
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Creating a Login and Registration System in PHP 8.1 - LaravelTuts.com</title>
    <!-- Add Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <div class="card my-5" >
                    <div class="card-body">
                        <h1 class="text-center ">Creating a Login and Registration System in PHP 8.1 - LaravelTuts.com</h1>
                    </div>
                </div>

                <h1 class="text-center my-5">Dashboard</h1>

                <p class="text-center">Welcome, <strong><?= $_SESSION['user_email']; ?></strong></p>

                <form action="dashboard.php" method="post" class="text-center">
                    <input type="submit" name="logout" value="Logout" class="btn btn-danger">
                </form>
            </div>
        </div>
    </div>

    <!-- Add Bootstrap JS and its dependencies -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
</body>
</html>
Creating the dashboard
Creating the dashboard

This code checks if the user is logged in by verifying the presence of a user ID in the session. If the user is not logged in, they are redirected to the login page. When the user clicks the “Logout” button, their session is destroyed, and they are redirected back to the login page.

Now you have a basic login and registration system in PHP 8.1 using MySQL as the database and styled with Bootstrap. You can build upon this foundation to create more advanced features and functionality for your web application.

Previews:

Login Page:

Login Page
Login Page

Registration Page:

Registration Page
Registration Page

Dashboard Page:

Dashboard Page
Dashboard Page

Conclusion:

In this tutorial, we have demonstrated how to create a simple login and registration system using PHP 8.1, MySQL, and Bootstrap. We covered the following steps:

  • Setting up the database and creating a table for user data
  • Establishing a database connection using PHP
  • Creating a registration form and handling user registration
  • Creating a login form and handling user authentication
  • Building a basic dashboard for authenticated users

This basic system serves as a foundation for user authentication in web applications. You can enhance the system by adding features such as email verification, password reset, user roles, and more advanced security measures like CSRF protection and rate limiting. Additionally, you can integrate this system into your existing projects or use it as a starting point for building more complex applications.

Remember to keep your code secure and up-to-date with the latest PHP and MySQL best practices, as well as regularly reviewing and updating your security measures to protect user data.

Share this:

Categorized in: