How to Create a Sign-Up and Log-In System in PHP

How to Create a Sign-Up and Log-In System in PHP

In this article, you will learn how to create a sign-up and login system in PHP and save the user's data in a MySQL database

A sign-up and log-in system is essential for a system so that a user can interact with the system's features.

In this article, you will learn how to:

  • create the sign-up and log-in form

  • save user data in a MySQL database table

  • retrieve user data from a MySQL database table

  • display relevant error messages

Prerequisites

  • HTML/CSS

  • PHP

  • Form Validation. You can check out my blog on Form Validation in PHP

  • SQL(minimal experience)

  • XAMPP or your preferred Apache environment installed

You can access the source code for this tutorial here.

How to Setup the Database

In the sign-up system, you will need a database where the user details will be stored and later retrieved when the user logs in.

How to Create a Database and Table in PHPMyAdmin

  1. Navigate to localhost/phpmyadmin

  2. Go to the Databases tab and create a database called users

  3. Create a table called userDetails

  4. Create the following columns

    💡
    Ensure the id column auto-increments and is the primary key

    The database and table are ready for use.

How to Connect to the Database

  1. In your htdocs folder, create a new directory.

  2. In your directory, create a db.php file

  3. Add the code that connects to the database

     <?php
     $host = 'localhost';
     $username = 'root';
     $password = '';
     // the name of the database you created above
     $database = 'users';
    
     $connection = mysqli_connect($host, $username, $password, $database);
    
     if ($connection) {
         echo "Connected to the database";
     } else {
         echo "Connection error";
     }
    
  4. The result should be:

    You can now access the database from your system. Let's get started with the sign-up page.

How to Create a Sign-Up System in PHP

The sign-up system should:

  • get the user's input

  • validate the user's input

  • add the data to the table successfully

  • display any errors

Creating the Sign-Up Form

  1. In your project directory, create a file named sign-up.php

  2. At the top of the document, include the database connection

     <?php
     include "./db.php";
     ?>
    
  3. Include the form-validate.php file which has form-validation functions from this blog.

     <?php
     include "./db.php";
     include "./form-validate.php";
     ?>
    
  4. Create a sign-up form that allows users to input their:

    • name

    • email

    • username

    • password

  5. Validate the user's inputs and display the error messages.

  6. Retain the user's input

Here's my code:

<?php
include "./db.php";
include "./form-validate.php";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_SPECIAL_CHARS);
    $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_SPECIAL_CHARS);

    // validating the name
    if (checkForEmpty($name)) {
        $nameError = "Please enter your name";
    } elseif (checkForInvalidText($name)) {
        $nameError = "Please only use characters and spaces. No special characters";
    }
    $formFields['name'] = $name;

    // validating the email
    if (checkForEmpty($email)) {
        $emailError = "Please enter your email";
    } elseif (checkForInvalidEmail($email)) {
        $emailError = "Please enter a valid email address";
    }
    $formFields['email'] = $email;

    //validating the username
    if (checkForEmpty($username)) {
        $usernameError = "Please enter a username";
    } elseif (checkForInvalidUsername($username)) {
        $usernameError = "Please use characters, numbers and underscores only";
    }
    $formFields['username'] = $username;

    // validating the password
    if (checkForEmpty($password)) {
        $passwordError = "Please enter your password";
    } elseif (checkForInvalidPassword($password)) {
        $passwordError = "Please use a strong password";
    }
    $formFields['password'] = $password;

    if (isset($nameError)) {
        $_SESSION['nameError'] = $nameError;
    }
    if (isset($emailError)) {
        $_SESSION['emailError'] = $emailError;
    }
    if (isset($usernameError)) {
        $_SESSION['usernameError'] = $usernameError;
    }
    if (isset($passwordError)) {
        $_SESSION['passwordError'] = $passwordError;
    }
    $_SESSION['formFields'] = $formFields;
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sign Up Page</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>

<body>
    <section class="p-5">
        <h1 class="text-center">Sign Up</h1>
        <p class="text-center fst-italic">Please enter all the fields</p>
        <form action="" method="post" class="w-25 mx-auto" style="min-width: 300px;">
            <div class="mb-3">
                <label for="name" class="form-label">Name</label>
                <input type="text" class="form-control" id="name" name="name" value="<?php echo isset($_SESSION['formFields']['name']) ? $_SESSION['formFields']['name'] : "" ?>">
                <div class="text-danger fw-bold"><?php echo isset($_SESSION['nameError']) ? $_SESSION['nameError'] : "" ?></div>
            </div>
            <div class="mb-3">
                <label for="email" class="form-label">Email address</label>
                <input type="email" class="form-control" id="email" name="email" value="<?php echo isset($_SESSION['formFields']['email']) ? $_SESSION['formFields']['email'] : "" ?>">
                <div class="text-danger fw-bold"><?php echo isset($_SESSION['emailError']) ? $_SESSION['emailError'] : "" ?></div>
            </div>
            <div class="mb-3">
                <label for="username" class="form-label">Username</label>
                <input type="text" class="form-control" id="username" name="username" value="<?php echo isset($_SESSION['formFields']['username']) ? $_SESSION['formFields']['username'] : "" ?>">
                <div class="text-danger fw-bold"><?php echo isset($_SESSION['usernameError']) ? $_SESSION['usernameError'] : "" ?></div>
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <input type="password" class="form-control" id="password" name="password" value="<?php echo isset($_SESSION['formFields']['password']) ? $_SESSION['formFields']['password'] : "" ?>">
                <div class="text-danger fw-bold"><?php echo isset($_SESSION['passwordError']) ? $_SESSION['passwordError'] : "" ?></div>
                <div class="form-text">
                    Your password should have:
                    <ul>
                        <li>at least one lowercase letter</li>
                        <li>at least one uppercase letter</li>
                        <li>at least one number</li>
                        <li>at least one special character</li>
                    </ul>
                </div>
            </div>

            <input type="submit" value="Sign Up" class="btn btn-outline-primary">
        </form>
    </section>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
</body>

</html>

How to Add Data to the MySQL Database

After the user's data is successfully validated, you should add the user input to the database.

  1. Check if there are no errors

  2. Insert data into the table

     <?php
     // Form Validation
     if (!$nameError || !$emailError || !$usernameError || !$passwordError) {
             $query = "INSERT INTO userDetails(`name`, email, username, `password`) VALUES (?, ?, ?, ?)";
    
             $stmt = $connection->prepare($query);
             $stmt->bind_param("ssss", $name, $email, $username, $password);
             $result = $stmt->execute();
    
             if ($result) {
                 echo "User saved successfully";
             } else {
                 echo "Error: User not saved";
             }
         }
     ?>
    
  3. Redirect to the homepage

     <?php
     <?php
     if (!$nameError || !$emailError || !$usernameError || !$passwordError) {
     // inserting data to the table
             if ($result) {
                 echo "User saved successfully";
                 header("Location: landing.php");
             } else {
                 echo "Error: User not saved";
             }
     }
     ?>
     ?>
    

After successfully signing up, it redirects to the landing page. It should work like this:

  1. Create an error message if the user can't sign up.

     <?php
     if (!$nameError || !$emailError || !$usernameError || !$passwordError) {
     // inserting data to the table
             if ($result) {
                 echo "User saved successfully";
                 header("Location: landing.php");
             } else {
                 $signupError = "Sign-up failed";
             }
     }
     ?>
     <!-- Before the submit button, add the error message -->
     <p class="text-danger fw-bold"><?echo isset($_SESSION['signupError']) ? $_SESSION['signupError'] : ""?></p>
    

Your sign-up page is fully functional. Let's get started with the login system.

How to Create a Log-In System in PHP

The log-in system should:

  • get the user's credentials and validate the data

  • check the database

  • redirect to the homepage

Creating the Log-In Form

  1. In your project's directory, create the log-in.php

  2. Include the db.php and the form-validate.php file

     <?php
     include "db.php";
     include "form-validate.php";
     ?>
    
  3. Create the login form

     <form action="" method="post" class="w-25 mx-auto" style="min-width: 300px;">
        <div class="mb-3">
            <label for="username" class="form-label">Username</label>
            <input type="text" class="form-control" id="username" name="username" value="<?php echo isset($_SESSION['formFields']['username']) ? $_SESSION['formFields']['username'] : "" ?>">
            <div class="text-danger fw-bold"><?php echo isset($_SESSION['usernameError']) ? $_SESSION['usernameError'] : "" ?></div>
         </div>
         <div class="mb-3">
            <label for="password" class="form-label">Password</label>
            <input type="password" class="form-control" id="password" name="password" value="<?php echo isset($_SESSION['formFields']['password']) ? $_SESSION['formFields']['password'] : "" ?>">
            <div class="text-danger fw-bold"><?php echo isset($_SESSION['passwordError']) ? $_SESSION['passwordError'] : "" ?></div>
         </div>
    
         <p class="text-danger fw-bold"><? echo isset($_SESSION['loginError']) ? $_SESSION['loginError'] : "" ?></p>
         <input type="submit" value="Sign Up" class="btn btn-outline-primary">
     </form>
    
  4. Validate the user's input

     <?php
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_SPECIAL_CHARS);
         $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_SPECIAL_CHARS);
    
         if (checkForEmpty($username) || checkForEmpty($password)) {
             $loginError = "Please fill all the fields";
         }else{
             $formFields['username'] = $username;
             $formFields['password'] = $password;
    
             $_SESSION['formFields'] = $formFields;
         }
    
     }
     ?>
    

How to Read Data from the MySQL Database

  1. Check if there are any validation errors

  2. Check if the user's credentials exist

     <?php
     if (!$usernameError || !$passwordError) {
      $query = "SELECT * FROM userDetails WHERE username='$username'";
      $result = $connection->query($query);
     }
     ?>
    
  3. Check if the user's password matches the one on the database

     <?php
     if ($result->num_rows > 0) {
         $row = $result->fetch_assoc();
         if ($row['password'] == $password) {
            echo "Logged in successfully";
            header("Location: landing.php");
         } else {
            $loginError = "Wrong password";
         }
     } else {
         $loginError = "User not found!";
     }
     ?>
    
  4. Display the relevant error messages

     <!-- Display error message before the submit button -->
     <?php
     if (isset($loginError)) {
       echo '<div class="text-center text-danger fw-bold my-3">' . $loginError . '</div>';
     }
     ?>
    

This is how the login works when:

  • the fields are empty

  • the user's credentials don't exist

  • the user enters the wrong password

  • the user successfully logs in

Conclusion

In this article, you learned how to:

  • create a database and table in PHPMyAdmin

  • create a sign-up form

  • create a log-in form

  • validate the form data

  • insert data into the table

  • get data from the table

  • display error messages

You can access the source code for this tutorial here.