Skip to main content

How to create user login and signup page in php and mysql.

Introduction

In this blog, we will create a user login and signup page in PHP and MYSQL. Login and signup feature is essential for any website to authenticate users. We create login and signup page for security purpose that protects some member only content or contain some features which is access by a user who is logged in.

For instance, In a blog website that contains blogs related to various topics, but some blogs are members only and does not access by a user who is not a member. To excess member only content you just need to signup with your email address and you can easily access members only content. Similarly, if you want to write a blog to publish your own content and share your knowledge. You have to login on that website. After login you will be able to publish your content on that blog website.

Learn how to create user login and signup page in PHP and MySQL. Before diving into this blog, you should have some basic knowledge of HTML and Bootstrap for front-end development and intermediate knowledge of PHP and MYSQL for back-end development and database management.

Prerequisites

  • HTML, CSS, and Bootstrap for front-end development
  • PHP for server-side scripting to handle back-end development
  • MySQL for database management
  • XAMPP to run code on your local computer

Table on Contents

We will cover this tutorial in 5 steps.
  1. Database Setup
  2. Creating the HTML form for Login and Signup
  3. Create a Database Configuration file
  4. Create PHP Script for Login and Signup page
  5. Create Logout Script

Step 1: Database Setup

A MySQL database is required to store user information such as fullname, email, and password in the database. We create database named "user_authentication". After creating database execute the following query for creating "users" table inside the database.


  CREATE TABLE `users` (
    `user_id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `full_name` varchar(255) NOT NULL,
    `email` varchar(255) NOT NULL UNIQUE,
    `password` varchar(255) NOT NULL
  );
 

Step 2: Creating the HTML form for Login and Signup

1. Signup Form - We create a HTML form with input fields for fullname, email, password, and confirm password. We will make sure that all input fields are fill by user for which we use required attribute that is default HTML attribute. Also we will make sure that user does not create multiple account with same email address. For which we use input type email in email input field. Also make sure always use POST method when we take user's information for security concern.

file name: signup.php

   
    <?php
        session_start();
        // Check user login or not
        // If user_id is set then we redirect user to dashboard page
        if(isset($_SESSION['user_id'])){
            header("location: dashboard.php");
        }
    ?>

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Sign Up</title>

        <!-- Bootstrap CDN Link  -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>

    <body class="bg-light d-flex align-items-center justify-content-center" style="min-height: 100vh;">
        <div class="container col-lg-4 col-md-6 p-4 shadow bg-white rounded">
            <h4 class="text-center">Create Account</h4>

            <!-- Error Message -->
            <?php if(isset($_SESSION['error'])): ?>
            <div class="alert alert-danger text-center">
                <?= $_SESSION['error']; ?>
            </div>
            <?php unset($_SESSION['error']); ?>
            <?php endif; ?>

            <!-- Success Message -->
            <?php if(isset($_SESSION['success'])): ?>
            <div class="alert alert-success text-center">
                <?= $_SESSION['success']; ?>
            </div>
            <?php unset($_SESSION['success']); ?>
            <?php endif; ?>

            <!-- Sign Up Form -->
            <form action="php/signup-process.php" method="post" class="d-flex flex-column gap-2">
                <div>
                    <label class="form-label">Full Name</label>
                    <input type="text" name="fullname" value="<?= isset($_SESSION['old']['fullname']) ? htmlspecialchars($_SESSION['old']['fullname']) : '' ; unset($_SESSION['old']['fullname']); ?>" class="form-control" required autocomplete="off">
                </div>
                <div>
                    <label class="form-label">Email</label>
                    <input type="email" name="email" value="<?= isset($_SESSION['old']['email']) ? htmlspecialchars($_SESSION['old']['email']) : '' ; unset($_SESSION['old']['email']); ?>" class="form-control" required autocomplete="off">
                </div>
                <div>
                    <label class="form-label">Password</label>
                    <input type="password" name="password" value="<?= isset($_SESSION['old']['password']) ? htmlspecialchars($_SESSION['old']['password']) : '' ; unset($_SESSION['old']['password']); ?>" class="form-control" required autocomplete="off">
                </div>
                <div>
                    <label class="form-label">Confirm Password</label>
                    <input type="password" name="confirm_password" value="<?= isset($_SESSION['old']['confirm_password']) ? htmlspecialchars($_SESSION['old']['confirm_password']) : '' ; unset($_SESSION['old']['confirm_password']); ?>" class="form-control" required autocomplete="off">
                </div>
                <button type="submit" name="submit" class="btn btn-primary mt-2 fw-medium">Sign Up</button>
            </form>

            <div class="d-flex justify-content-center mt-3">
                Already have an account? <a href="login.php" class="ms-1 fw-medium link-underline link-underline-opacity-0 link-underline-opacity-100-hover">Login</a>
            </div>
        </div>
    </body>
    </html>
   

In this code,
  1. If user is already created an account and  already then we redirect user to dashboard.php. We are using global variable $_SESSION[] to check user_id is set or not.
  2. We use Bootstrap for styling to avoid writing CSS from the scratch.
  3. To display error and success we use $_SESSION[] variable and after displaying the error and success message we unset the session variable.

Below is the screenshot of the above code for signup page.



2. Login Form - A login form is created with input field for email and password. Here also we make sure that both input fields are filled by user. For thin we use required attribute which is a default HTML attribute and for email we use input type email that checks the email is a valid email.

file name: login.php

   
    <?php
        session_start();
        // Check user login or not
        // If user_id is set then we redirect user to dashboard page
        if(isset($_SESSION['user_id'])){
            header("location: dashboard.php");
        }
    ?>

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Login</title>

        <!-- Bootstrap CDN Link  -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>

    <body class="bg-light d-flex align-items-center justify-content-center min-vh-100">
        <div class="container col-lg-4 col-md-6 col-8 d-flex flex-column
        gap-3 border bg-white rounded shadow p-4 ">
            <h4 class="text-center">Login</h4>

            <!-- Error Message -->
            <?php if(isset($_SESSION['error'])): ?>
            <div class="alert alert-danger text-center">
                <?= $_SESSION['error']; ?>
            </div>
            <?php unset($_SESSION['error']); ?>
            <?php endif; ?>

            <!-- Login Form -->
            <form action="php/login-process.php" method="POST" class="d-flex flex-column gap-2">
                <div>
                    <label class="form-label">Email Address</label>
                    <input type="email" name="email" value="<?= isset($_SESSION['old']['email']) ? htmlspecialchars($_SESSION['old']['email']) : '' ; unset($_SESSION['old']['email']); ?>" class="form-control" required autocomplete="off">
                </div>
                <div>
                    <label class="form-label">Password</label>
                    <input type="password" name="password" value="<?= isset($_SESSION['old']['password']) ? htmlspecialchars($_SESSION['old']['password']) : '' ; unset($_SESSION['old']['password']); ?>" class="form-control" required autocomplete="off">
                </div>
                <button type="submit" name="submit" class="btn btn-primary mt-2 fw-medium">Login</button>
            </form>
       
            <div class="d-flex justify-content-center">Don't have an account? <a href="signup.php" class="ms-1 fw-medium link-underline link-underline-opacity-0 link-underline-opacity-100-hover">Sign up</a></div>
        </div>
    </body>
    </html>
   

In this code,
  1. First we check if user is already login or not using super global variable $_SESSION[] if user_id is set then we redirect user to dashboard.php.
  2. We use Bootstrap for styling to avoid writing CSS from the scratch.
  3. To display error and success we use $_SESSION[] variable and after displaying the error and success message we unset the session variable.

Below is the screenshot of the above code for login page.


3. User Dashboard - We create a file named dashboard.php. In this below code we check if user_id set or not, If user_id is set that means user is login. After successfully login user redirect to user dashboard page. In user dashboard page we display a welcome message and a logout button is created for logout.

file name: dashboard.php

   
    <?php
        session_start();
        include_once "php/config.php";
        // Check user login or not
        // If user_id is not set then we redirect user to login page
        if(!isset($_SESSION['user_id'])){
            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</title>

        <!-- Bootstrap CDN Link   -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body class="bg-light d-flex align-items-center justify-content-center pt-4">

        <div class="container col-lg-10 col-md-8 col-sm-6 col-10 border bg-white rounded shadow p-4">
            <h1 class="text-center mb-4">Dashboard</h1>
           
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-center">
                <p class="fs-5 fw-normal mb-3 mb-md-0">
                    Welcome <strong><?php echo $_SESSION['fullname']; ?></strong>, you are successfully logged in.
                </p>
                <a href="php/logout.php" class="btn btn-danger fs-5 fw-medium">Logout</a>
            </div>
        </div>

    </body>
    </html>
   


Below is the screenshot of the above code for dashboard page.


Step 3: Create a Database Configuration file

We created a configuration file named config.php to establish a connection with the database. This script contains database credentials such as hostname, username, database name, and password.

file name: config.php

 
  <?php
      // Create Connection with Localhost
      $hostname = "localhost";
      $username = "root";
      $password = "";
      $dbname = "user_authentication";

      $conn = mysqli_connect($hostname, $username, $password, $dbname);
      if(!$conn){
        echo "Database connection error". mysqli_connect_error($error);
      }

  ?>
 

Step 4: Create PHP Script for Login and Signup page

1. Signup Script - This PHP script handles user registration securely. It validates inputs (required fields, email format, matching passwords), checks if the email already exists, and safely stores new users in the database using prepared statements. Passwords are hashed with password_hash() before saving, ensuring security. Error and success messages are stored in sessions so they can be displayed on the signup page.

file name: signup-process.php

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

    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
        $fullname = mysqli_real_escape_string($conn, $_POST['fullname']);
        $email = mysqli_real_escape_string($conn, $_POST['email']);
        $password = mysqli_real_escape_string($conn, $_POST['password']);
        $confirm_password = mysqli_real_escape_string($conn, $_POST['confirm_password']);

        // Store values in session (so user doesn’t need to retype)
        $_SESSION["old"] = [
            "fullname" => $fullname,
            "email" => $email
        ];

        if(!empty($fullname) && !empty($email) && !empty($password) && !empty($confirm_password)){
            if(filter_var($email, FILTER_VALIDATE_EMAIL)){
                if($password === $confirm_password){
                    $stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE email = ?");
                    mysqli_stmt_bind_param($stmt, "s", $email);
                    mysqli_stmt_execute($stmt);
                    $result = mysqli_stmt_get_result($stmt);

                    if(mysqli_num_rows($result)>0){
                        echo "This email is already registered!";
                    }else{
                        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

                        $stmt = mysqli_prepare($conn, "INSERT INTO users (fullname, email, password) VALUES (?, ?, ?)");
                        mysqli_stmt_bind_param($stmt, "sss", $fullname, $email, $hashed_password);

                        if(mysqli_stmt_execute($stmt)){
                            $_SESSION['success'] = "Registration successful! You can now <a href='login.php'>Login</a>.";
                            header("Location: ../signup.php");
                            exit;
                        }else{
                            $_SESSION['error'] = "Invalid email address!";
                            header("Location: ../signup.php");
                            exit;
                        }
                        mysqli_stmt_close($stmt);
                    }

                }else{
                    $_SESSION['error'] = "Passwords do not match!";
                    header("Location: ../signup.php");
                    exit;
                }
            }else{
                $_SESSION['error'] = "Invalid email address!";
                header("Location: ../signup.php");
                exit;
            }
        }else{
            $_SESSION['error'] = "All fields are required!";
            header("Location: ../signup.php");
            exit;
        }
    }else{
        $_SESSION['error'] = "Something went wrong! please try again.";
        header("Location: ../signup.php");
        exit;
    }



2. Login Script - This PHP script manages the user login process. It validates input fields, checks if the email exists in the database, and verifies the entered password using password_verify(). On success, it starts a session and stores user details (like user_id and fullname) for authentication. If login fails, it returns clear error messages via session variables.

file name: login-process.php

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

    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
        $email = mysqli_real_escape_string($conn, $_POST['email']);
        $password = mysqli_real_escape_string($conn, $_POST['password']);

        // Store values in session (so user doesn’t need to retype)
        $_SESSION["old"] = [
            "email" => $email
        ];

        if (!empty($email) && !empty($password)) {
            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $stmt = mysqli_prepare($conn, "SELECT * FROM `users` WHERE email = ?");
                mysqli_stmt_bind_param($stmt, "s", $email);
                mysqli_stmt_execute($stmt);
                $result = mysqli_stmt_get_result($stmt);

                if (mysqli_num_rows($result) > 0) {
                    $row = mysqli_fetch_assoc($result);
                    if (password_verify($password, $row['password'])) {
                        $_SESSION['user_id'] = $row['user_id'];
                        $_SESSION['fullname'] = $row['fullname'];
                        header("Location: ../dashboard.php");
                        exit;
                    } else {
                        $_SESSION['error'] = "Invalid password!";
                        header("Location: ../login.php");
                        exit;
                    }
                } else {
                    $_SESSION['error'] = "$email does not exist!";
                    header("Location: ../login.php");
                    exit;
                }
                mysqli_stmt_close($stmt);
            } else {
                $_SESSION['error'] = "$email is not a valid email!";
                header("Location: ../login.php");
                exit;
            }
        } else {
            $_SESSION['error'] = "All input fields are required!";
            header("Location: ../login.php");
            exit;
        }
    }
    ?>


Step 5: Create Logout Script

We create a logout file named logout.php to logout from the user dashboard. After clicking the logout button below code is executed. In this code we unset and destroy the session and redirect to login.php page.

file name: logout.php

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

        if(isset($_SESSION['user_id'])){
            session_unset();
            session_destroy();
            header("location: ../login.php");
            exit;
        }
    ?>

Conclusion

In this blog, we explored how to create user login and signup page in PHP and MySQL. After created login and signup page you are able to create a user authentication feature in PHP. In the login form you can add more features like forgot password, remember me, and verify email by sending a verification link to the user's email address.

Comments

Popular posts from this blog

Leetcode SQL 50 interview questions with solution: A Guide for Coders

Introduction Hi coders, In this blog, we will tackle SQL questions from LeetCode. If you're a coder, a computer science student, or simply interested in coding, you may be familiar with LeetCode. It's a platform where coding enthusiasts practice problems to enhance their critical thinking and problem-solving skills. Most of us practice programming questions on leetcode so here we practice SQL questions which is taken from leetcode. We'll start with basic SQL questions focused on SELECT , joins, and aggregate functions. Once we've covered these foundational topics, we'll transition to more advanced concepts. Before diving into the questions, ensure you have a basic understanding of SQL syntax and statements, including SELECT , various joins (self join, left join, right join, outer join), and basic aggregate functions. Here are some SQL interview questions with solution: Q1 1757. Recyclable and Low Fat Products SELECT product_id FROM Products WHERE low_fats ...

How to Create a Responsive Website Using CSS.

Responsive Website Introduction Creating a responsive website is not an option, It's number one priority for a developer to make a website responsive. A responsive website adjusts according to different screen sizes, providing an optimal user experience on desktops, tablets, and mobile devices. For creating a responsive website, You don't need JavaScript to make your website responsive, HTML and CSS are enough. In this guide, we will walk through the key techniques to build a fully responsive web page from scratch. Why is Responsiveness Important? A responsive website offers several benefits, including: Better User Experience - Ensures your content is readable on all devices. Improved SEO Ranking - Mobile-friendly websites rank higher in search results. Faster Loading Times - Optimized layouts prevent unnecessary resource consumption. Increased Engagement - Users stay longer on a site that adapts well to their screen. Now, let's dive into the essential techniques to cre...

What is Git and GitHub. Difference Between Git and GitHub. Workflow of Git.

Introduction In this blog, we will dive into a Git and GitHub, understand their differences, and go over the typical workflow when using GitHub. Whether you are new to version control or simply curious about how these tools work together, this guide will walk you through the essential concepts and processes you need to know. What is Git? Git is a Distributed Version Control System (DVCS) that efficiently manages code changes across multiple contributors. It helps developers to monitor and manage changes in their code efficiently. Git was created by Linus Torvalds on April 7, 2005. It is widely used in developer community for its collaborative features, allowing developers to work on the same project, whether the project is small or large. You can efficiently monitor code modifications and preserve a detailed history of changes. Git is free and open-source, designed to handle everything from individual projects to complex ones. Developers can track every modification, create branches fo...