How to Create Login & Register System with PHP and MySQLi

Category
Tutorial
Reading
5 mins
Views
21.9K
Posting
14 Aug 2023

In modern website applications, the registration system is commonly used in various modern applications, this is done to authenticate users to fully use their services. The login and registration system also has many benefits in your digital business, both membership or paid services.

Login or registration system is a security mechanism on the website to limit access to certain pages. In this tutorial, we will create a complete login or registration system along with a logout feature, password reset and a simple page to display data when successfully logged in using PHP. Let's start first by creating a table in the database.

 

 

1. First, create the database table first

Before entering the other stages, creating database tables is something important, used to store and read the data needed. Create a new database and run the query below to create a users table in the MySQL database.

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

Copy and paste the line of code into the form in the SQL tab in phpmyadmin.

 

2. Create the database configuration file

In order for the database to be connected to the application, it takes a few lines of code to run it, create a new file called config.php to store data for the database, please copy and paste the lines of code below to continue.

Change the database username, database password and table name according to what you created yourself.

<?php // Configuration

/*
* genelify.com
*/

define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'test');

// Connect with database
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

// Check connection
if ($conn === false) {
    die("Error: failed to connected. " . mysqli_connect_error());
}

Change the database username, database password and table name according to what you created yourself.

 

3. Create a login system with PHP and HTML display the form

After finishing creating tables and configuring the database, we go to the next step, namely creating a login form or login system. At this stage, there is a form that functions to access the page by entering the required data such as name and password.

It is used to verify and authenticate data already stored in the database. If the name and password do not match those in the database, then access will be denied by the server. We are using Bootstrap as the CSS framework to handle the front end on this page.

To create this login form or login system, create a new php file and you can match the file name to login.php and just follow the code below.

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Login</title>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
     <style>
         body{ font: 14px sans-serif; background: #efefef;}
         .wrapper{ width: 380px; padding: 20px; margin:0 auto; displays: blocks; margin-top: 60px; background: #fff;}
     </style>
</head>
<body>
     <div class="wrapper">
         <h2>Login</h2>
         <p>Please fill in the data needed to access your page.</p>

         <?php
         if(!empty($login_err)){
             echo '<div class="alert alert-danger">' . $login_err . '</div>';
         }
         ?>

         <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
             <div class="form-group">
                 <label>Name</label>
                 <input type="text" name="name" class="form-control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $name; ?>">
                 <span class="invalid-feedback"><?php echo $name_err; ?></span>
             </div>
             <div class="form-group">
                 <label>Password</label>
                 <input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
                 <span class="invalid-feedback"><?php echo $password_err; ?></span>
             </div>
             <div class="form-group">
                 <input type="submit" class="btn btn-primary" value="Login">
             </div>
             <p>Don't have an account? <a href="registration.php">Register here!</a>.</p>
         </form>
     </div>
</body>
</html>

​And then follow the PHP code below right before the <!DOCTYPE html> tag.

<?php // login.php

/*
* genelify.com
*/

// Initialize session
session_start();
 
// Check if the user is already logged in, if so then it will be redirected to home
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
     header("location: home.php");
     exit;
}
 
// Add database configuration
require_once "config.php";
 
// Define each variable with an empty value
$name = $password = "";
$name_err = $password_err = $login_err = "";
 
// Process the data if the form has been submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
     // Checks if name is empty
     if(empty(trim($_POST["name"]))){
         $name_err = "Please enter your name.";
     } else{
         $name = trim($_POST["name"]);
     }
    
     // Checks if the password is empty
     if(empty(trim($_POST["password"]))){
         $password_err = "Please enter your password.";
     } else{
         $password = trim($_POST["password"]);
     }
    
     // Validate name and password
     if(empty($name_err) && empty($password_err)){

         // Connect with database
         $sql = "SELECT id, name, password FROM users WHERE name = ?";
        
         if($stmt = mysqli_prepare($conn, $sql)){

             // Bind variables into the statement as parameters
             mysqli_stmt_bind_param($stmt, "s", $param_name);
            
             // Set parameters
             $param_name = $name;
            
             // Execute
             if(mysqli_stmt_execute($stmt)){

                 // Save result
                 mysqli_stmt_store_result($stmt);
                
                 // Checks if the name is already in use, if yes do the next validation
                 if(mysqli_stmt_num_rows($stmt) == 1){

                     // Bind the result variable
                     mysqli_stmt_bind_result($stmt, $id, $name, $hashed_password);

                     if(mysqli_stmt_fetch($stmt)){
                        
                         // Perform password validation
                         if(password_verify($password, $hashed_password)){

                             // If the password is successful, start into the session
                             session_start();
                            
                             // Put data into session variables
                             $_SESSION["loggedin"] = true;
                             $_SESSION["id"] = $id;
                             $_SESSION["name"] = $name;
                            
                             // Redirect user to home page
                             header("location: home.php");
                         } else{
                             // Displays an error if the password does not match
                             $login_err = "Passwords do not match.";
                         }
                     }
                 } else {
                     // Displays an error if the name or password does not match
                     $login_err = "Incorrect username or password.";
                 }
             } else {
                 echo "Seems like an error, please try again later!";
             }

             // Close statement
             mysqli_stmt_close($stmt);
         }
     }
    
     // Close connection
     mysqli_close($conn);
}
?>

All the data needed will later be entered into the session variable to allow access to the main page. When finished, try running it into the browser, the resulting output will be like this:

 

How to Create Login and Register With PHP and MySQLi - Login System

 

4. Create a registration system, along with HTML for the frontend

The next step is to create a registration system to send data to the server to be stored and used when the user logs in. This special page will display a form such as name, password and password confirmation that allows the user to register himself into the website application that we have created.

In this special code, we insert PHP and HTML code, the PHP code is used to process data entered by the user such as validation, storing data in the database and displaying errors if there are errors in filling out forms, duplication of names and so on. Then HTML is used to display the predefined form, we use Bootstrap as the CSS framework to handle the front end on this page.

Create a new file registration.php and just follow the syntax code below into the file.

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Registration</title>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
     <style>
         body{ font: 14px sans-serif; background: #efefef;}
         .wrapper{ width: 380px; padding: 20px; margin:0 auto; displays: blocks; margin-top: 60px; background: #fff;}
     </style>
</head>
<body>
     <div class="wrapper">
         <h2>Registration</h2>
         <p>Please fill in the form below to continue.</p>
         <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
             <div class="form-group">
                 <label>Name</label>
                 <input type="text" name="name" class="form-control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $name; ?>">
                 <span class="invalid-feedback"><?php echo $name_err; ?></span>
             </div>
             <div class="form-group">
                 <label>Password</label>
                 <input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $password; ?>">
                 <span class="invalid-feedback"><?php echo $password_err; ?></span>
             </div>
             <div class="form-group">
                 <label>Confirm Password</label>
                 <input type="password" name="confirm_password" class="form-control <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $confirm_password; ?>">
                 <span class="invalid-feedback"><?php echo $confirm_password_err; ?></span>
             </div>
             <div class="form-group">
                 <input type="submit" class="btn btn-primary" value="Submit">
                 <input type="reset" class="btn btn-secondary ml-2" value="Reset">
             </div>
             <p>Already have an account? <a href="login.php">Login here!</a>.</p>
         </form>
     </div>
</body>
</html>

And then place the PHP code below right before the <!DOCTYPE html> tag.

<?php // registration.php

/*
* genelify.com
*/

// Call the config database
require_once "config.php";
 
// Define each variable with an empty value
$name = $password = $confirm_password = "";
$name_err = $password_err = $confirm_password_err = "";
 
// Do it if the data has been entered into the form
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
     // Check if name is empty
     if(empty(trim($_POST["name"])))
     {
         $name_err = "Please enter a name.";
     }
     // Detect disallowed characters using regex
     elseif(!preg_match('/^[a-zA-Z0-9_]+$/', trim($_POST["name"])))
     {
        $name_err = "Names can only contain a combination of words, numbers or underscores.";
     }
     else {
         // Connecting with the database
         $sql = "SELECT id FROM users WHERE name = ?";
        
         if($stmt = mysqli_prepare($conn, $sql)){
             // Used to bind variables to marker parameters of prepared statements.
             mysqli_stmt_bind_param($stmt, "s", $param_name);
            
             // Set up the name parameter
             $param_name = trim($_POST["name"]);
            
             // Execute
             if(mysqli_stmt_execute($stmt)){

                 mysqli_stmt_store_result($stmt);
                
                 if(mysqli_stmt_num_rows($stmt) == 1){
                     $name_err = "This name is already registered!";
                 } else{
                     $name = trim($_POST["name"]);
                 }
             }
             else {
                 // Returns an error if the statement failed to execute
                 echo "There seems to be an error, please try again later.";
             }

             // Close statement
             mysqli_stmt_close($stmt);
         }
     }
    
     // Password validation
     if(empty(trim($_POST["password"]))){
         $password_err = "Please enter a password.";
     } elseif(strlen(trim($_POST["password"])) < 6){
         $password_err = "Password must be up to 6 characters long.";
     } else{
         $password = trim($_POST["password"]);
     }
    
     // Validate password confirmation
     if(empty(trim($_POST["confirm_password"]))){
         $confirm_password_err = "Please confirm password.";
     } else{
         $confirm_password = trim($_POST["confirm_password"]);
         if(empty($password_err) && ($password != $confirm_password)){
             $confirm_password_err = "Passwords do not match.";
         }
     }
    
     // Check for errors before executing into the database
     if(empty($name_err) && empty($password_err) && empty($confirm_password_err)){
        
         // Set up a connection with the database
         $sql = "INSERT INTO users (name, password) VALUES (?, ?)";
         
         if($stmt = mysqli_prepare($conn, $sql)){

             // Used to bind variables to marker parameters of prepared statements.
             mysqli_stmt_bind_param($stmt, "ss", $param_name, $param_password);
            
             // Set parameters of name and password
             $param_name = $name;
             $param_password = password_hash($password, PASSWORD_DEFAULT); // change password to hash code
            
             // Execute
             if(mysqli_stmt_execute($stmt)){
                 // Redirect if successful
                 header("location: login.php");
             } else{
                 // Returns an error if the statement failed to execute
                 echo "There seems to be an error, please try again later.";
             }

             // Close statement
             mysqli_stmt_close($stmt);
         }
     }
    
     // Close connection with database
     mysqli_close($conn);
}
?>

We use password_hash to change the password into a hash algorithm to make it more secure, then match it with the password confirmation form to strengthen the registration system by using the password_verify function. When finished, try running it into the browser, the resulting output will be like this:

 

How to Create Login and Register With PHP and MySQLi - Register System

 

5. Create a logout system

This logout feature actually has a simple system, when the user successfully logs into the main page and the user logs out, then all data in the session variable will be deleted and the page will be redirected to the login page to re-enter. To add this logout feature, please copy and paste the syntax below into a new file called logout.php.

<?php // Logout.php

/*
* genelify.com
*/

// Initialize session
session_start();
 
// Delete all variables in session
$_SESSION = array();
 
// Destroy session.
session_destroy();
 
// Redirect to login page
header("location: login.php");
exit;

 

6. Homepage section

This page is the main page when the user has successfully logged in and can do other things such as changing passwords and logging out. In this main page, we only display some simple text which indicates the user has successfully logged in.

And to avoid XSS attacks, we add the htmlspecialchars function to handle this. This function will change any form of script into special characters that cannot be executed by the browser. We are using Bootstrap as the CSS framework to handle the front end on this page. To add this main page, create a new file called home.php and the contents of the syntax are:

<?php // Home.php

/*
* genelify.com
*/

// Initialize session
session_start();
 
// Check if the user is logged in, if not then redirect to the login page, but if yes then continue
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
     header("location: login.php");
     exit;
}
?>
 
<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Welcome <?php echo htmlspecialchars($_SESSION["name"]); ?> - Home</title>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
     <style>
         body{ font: 14px sans-serif; text-align: center; background: #efefef;}
     </style>
</head>
<body>
     <h1 class="mt-5">Hello, <b><?php echo htmlspecialchars($_SESSION["name"]); ?></b>. Welcome back.</h1>
     <p class="mb-4">Successfully logged in, please if you want to change your password, you can click the reset password button below</p>
     <p>
         <a href="reset-password.php" class="btn btn-primary">Reset password</a>
         <a href="logout.php" class="btn btn-danger ml-3">Logout</a>
     </p>
</body>
</html>

When finished, try running it into the browser, the resulting output will be like this:

 

How to Create Login and Register With PHP and MySQLi - Welcome page

 

7. Create a password reset system (optional)

Actually this feature is optional, but to complete the login and registration system, without the password reset feature it will be lacking, therefore we are adding this feature to complement it with other features.

The system in resetting this password is actually a simple system by changing the existing password with a new one on the main page after the user has successfully logged in, the new updated password still uses the hash algorithm to make it more secure. To add this password reset feature, move the syntax below into a new file called reset-password.php.

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Reset Password</title>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
     <style>
         body{ font: 14px sans-serif; background: #efefef;}
         .wrapper{ width: 380px; padding: 20px; margin:0 auto; displays: blocks; margin-top: 60px; background: #fff;}
     </style>
</head>
<body>
     <div class="wrapper">
         <h2>Reset Password</h2>
         <p>Please fill in the form below to replace the old password with a new one.</p>
         <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
             <div class="form-group">
                 <label>New password</label>
                 <input type="password" name="new_password" class="form-control <?php echo (!empty($new_password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $new_password; ?>">
                 <span class="invalid-feedback"><?php echo $new_password_err; ?></span>
             </div>
             <div class="form-group">
                 <label>Confirm password</label>
                 <input type="password" name="confirm_password" class="form-control <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>">
                 <span class="invalid-feedback"><?php echo $confirm_password_err; ?></span>
             </div>
             <div class="form-group">
                 <input type="submit" class="btn btn-primary" value="Submit">
                 <a class="btn btn-link ml-2" href="home.php">Cancel</a>
             </div>
         </form>
     </div>
</body>
</html>

And then place the PHP code below right before the <!DOCTYPE html> tag.

<?php // reset-password.php

/*
* genelify.com
*/

// Initialize session
session_start();
 
// Check if the user is logged in, if not redirect to the login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
     header("location: login.php");
     exit;
}
 
// Call the config database
require_once "config.php";
 
// Variable definition with empty value
$new_password = $confirm_password = "";
$new_password_err = $confirm_password_err = "";
 
// Process the data if the user submits the form
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
     // Password validation
     if(empty(trim($_POST["new_password"]))){
         $new_password_err = "Please enter your new password.";
     } elseif(strlen(trim($_POST["new_password"])) < 6){
         $new_password_err = "Please enter a new password with a maximum of 6 characters";
     } else{
         $new_password = trim($_POST["new_password"]);
     }
    
     // Validate password confirmation
     if(empty(trim($_POST["confirm_password"]))){
         $confirm_password_err = "Please confirm your new password.";
     } else{
         $confirm_password = trim($_POST["confirm_password"]);
         if(empty($new_password_err) && ($new_password != $confirm_password)){
             $confirm_password_err = "Passwords do not match.";
         }
     }
        
     // Check the input if there are no errors
     if(empty($new_password_err) && empty($confirm_password_err)){

         // Connect with database
         $sql = "UPDATE users SET password = ? WHERE id = ?";
        
         if($stmt = mysqli_prepare($conn, $sql)){

             // Bind variables into the statement as parameters
             mysqli_stmt_bind_param($stmt, "si", $param_password, $param_id);
            
             // Set parameters
             $param_password = password_hash($new_password, PASSWORD_DEFAULT);
             $param_id = $_SESSION["id"];
            
             // Execute
             if(mysqli_stmt_execute($stmt)){

                 // Password updated successfully, delete session and redirect to login page
                 session_destroy();
                 header("location: login.php");
                 exit();
             } else{
                 echo "Seems like an error, please try again later.";
             }

             // Close statement
             mysqli_stmt_close($stmt);
         }
     }
    
     // Close connection
     mysqli_close($conn);
}
?>

When finished, try running it into the browser, the resulting output will be like this:

 

How to Create Login and Register With PHP and MySQLi - Reset Password System

 

Closing

That's a tutorial on making a simple login system using PHP, MySQL and Bootstrap. To complete all login systems, we add other features such as registration, logout, password reset, the main page to make it even more stable.

Share