Add Authentication to Any PHP App Using MySQL

PHP is an open-source server-side scripting language that can be embedded into HTML to build web applications. It is used for developing dynamic web applications and connecting the application to a database.

In this guide, you will learn how to build an authentication system using PHP and MySQL databases. We expect you to know the basics of PHP and MySQL before getting started.

Building the Layout Using HTML and Bulma CSS

The front end of this project is built using HTML and Bulma CSS. Bulma CSS is one of the popular CSS frameworks used for designing web pages. You can use Bulma CSS by importing the minified CSS from the CDN into your PHP file.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">

Integrating MySQL Database

MySQL is a relational SQL database management system used for performing CRUD operations on the data. This web application will use phpMyAdmin for managing the database.

phpMyAdmin is a free software tool written in PHP, intended to handle the administration of MySQL over the web.

You can install the phpMyAdmin by setting up a WAMP server on your Windows machine (or XAMPP on Linux) and visit the following URL

http://localhost/phpmyadmin

The screen will look like this:

phpMyAdmin administration page

Creating the Database

You can create the database either by using SQL queries or via the GUI provided by phpMyAdmin. In this application, the name of the database is auth, and the table name is also users. The attributes of the table are id, username, email, and password.

Here’s how you can create the database and table using SQL commands:

 

CREATE DATABASE auth;
CREATE TABLE users(
   id int,
   username varchar(255),
   email varchar(255),
   password varchar(500),
);

Connecting the App to the Database

Create a file named db.php in your project folder, where you will connect your database and import this file into other PHP files for using it.

The connection is established using the mysqli_connect() method. This method accepts four arguments: the server name, the user, the password, and the database name.

You can use the $connection variable while running queries by importing the db.php file into other PHP files.

<?php
   $connection = mysqli_connect("localhost", "root", "", "auth") ;
?>

Sign Up Using PHP

The first phase of building an authentication system involves registration or sign up. The frontend layout of the signup page has a form with an action that makes a POST request on the page. It has four input fields: username, email, password, and confirm password.

 <form class="card m-3 p-6 m-5 container mx-auto" action="./register.php" method="POST">
   
       <h1 class="title is-1 has-text-center">Register Here</h1>
       <input class="input is-primary mt-4" type="text" name="username"  placeholder="Username">
       <?php if ($usernameErrorMsg != "") echo "<p class='is-size-6 is-danger is-light has-text-danger'>$usernameErrorMsg</p>" ?>
       
       <input class="input is-primary mt-4" type="email" name="email"  placeholder="Email">
       <?php if ($emailErrorMsg != "") echo "<p class='is-size-6 is-danger is-light has-text-danger'>$emailErrorMsg</p>" ?>
       
       <input class="input is-primary mt-4" type="password" name="password" placeholder="Password">
       <?php if ($passwordErrorMsg != "") echo "<p class='is-size-6 is-danger is-light has-text-danger'>$passwordErrorMsg</p>" ?>
       
       <input class="input is-primary mt-4" type="password" name="confirm-password" placeholder="Confirm Password">
       <?php if ($confirmPasswordErrorMsg != "") echo "<p class='is-size-6 is-danger is-light has-text-danger'>$confirmPasswordErrorMsg</p>" ?>
       
       <button type="submit" name="submit" class="button is-primary mt-4">Register</button>
       <p class="mt-2 text-center">Already have an account ? <a href="./login.php">Login</a></p> 
</form>

Register page layout

The isset() method checks if the button is clicked or not, as it can access the Register button using the $_POST[] superglobal.

Before all this, you need to import the db.php file into the register.php file. There are a couple of variables declared for the input validation. Check out the code below.

include "./db.php";
$error = "";
$emailErrorMsg = "";
$usernameErrorMsg = "";
$passwordErrorMsg = "";
$confirmPasswordErrorMsg = "";

Input Validation on the Register Page

Before proceeding with the input validation, you need to get access to the values of the input elements using $_POST[].

The mysqli_real_escape_string() method helps to remove special characters from the string as they might cause malicious actions while performing query operations.

 

$username = mysqli_real_escape_string($connection, $_POST["username"]);
$email = mysqli_real_escape_string($connection, $_POST["email"]);
$password = mysqli_real_escape_string($connection, $_POST["password"]);
$confirmPassword = mysqli_real_escape_string($connection, $_POST["confirm-password"]);
    if($username == ""){
       $usernameErrorMsg = "Please enter your username";
         }
         if($email == ""){
             $emailErrorMsg = "Please enter the email"; 
         }else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
            $emailErrorMsg = "Please enter a valid email";  
         }
         if($password == ""){
             $passwordErrorMsg = "Enter your password";
         }
         if($confirmPassword == ""){
             $confirmPasswordErrorMsg = "Enter confirm password";
         }
          if(strlen($password) < 6){
             $passwordErrorMsg = "Enter a password greater than 6 characters";
         }else if($password!=$confirmPassword){
             $confirmPasswordErrorMsg = "Password and Confirm Password field should be same";
         }
Register page with validation errors

First of all, you check if the fields are empty or not. For the email input field, you need to check if the user has entered a valid email or not using the filter_var() method. The length of the password field should be greater than 6. These are the basic validations you need to take care of while building any application.

If there are no errors, you can proceed with performing query commands on the register.php file.

if($error == "" && $emailErrorMsg == "" && $passwordErrorMsg == "" && $confirmPasswordErrorMsg == ""){
          $query = "SELECT * FROM auth WHERE email = '$email'";
                  $findUser = mysqli_query($connection, $query);
                  $resultantUser = mysqli_fetch_assoc($findUser);
      
                  if($resultantUser){
                      $error = "User already exists";
                  }
                  $password = md5($password);
                  $query = "INSERT INTO auth (username, email, password) VALUES('$username', '$email', '$password')";
                  $insertUser = mysqli_query($connection, $query);
      
                  $_SESSION['username'] = $username;
                  $_SESSION['email'] = $email;
                  header("location: home.php");
}

You have to run a query that checks if the email already exists in the database or not. The mysqli_query() method is used to perform all the query operations. You have to pass the result of the query in the mysqli_query_assoc() method. This method converts the result into an associative array of strings.

If the user already exists, you need to display an error with the message: User already exists. Else, you need to insert the fields in the database. As it’s not a good practice to store password strings in plaintext, the md5() method will convert the password into a hash, and then save it.

Once the user is stored in the database, you need to load the username or email in the $_SESSION[] superglobal and redirect the user to the home page.

A Look at the Home Screen

The user can access the home page only if they are logged in. On the home page, you need to check if the SESSION exists or not. If there is no SESSION set, you need to redirect the user to the login page.

Layout for home page

Login Using PHP

In this application, the user will log in using email and password. The HTML layout for login.php:

<form class="card m-3 p-6 m-5 container  mx-auto" action="./login.php" method="POST">
       <h1 class="title is-1 has-text-center has-text-black">Login Here</h1>
       <?php if ($error != "") echo " <div class='button is-danger is-light'>$error</div>" ?>
       <input class="input is-primary mt-4"  name="email" type="email" placeholder="Email">
       <?php if ($emailErrorMsg != "") echo "<p class='is-size-6 is-danger is-light has-text-danger'>$emailErrorMsg</p>" ?>
       
       <input class="input is-primary mt-4"  name="password" type="password" placeholder="Password">
       <?php if ($passwordErrorMsg != "") echo "<p class='is-size-6 is-danger is-light has-text-danger'>$passwordErrorMsg</p>" ?>
       <button class="button is-primary mt-4" type="submit" name="submit">Login</button>
       <p>Don't have an account? <a href="./register.php">Register here</a></p>
   </form>
Layout of login page

Authenticating the User

You need to validate the inputs similar to how it was done while registering the user.

$email = mysqli_real_escape_string($connection, $_POST["email"]);
      $password = mysqli_real_escape_string($connection, $_POST["password"]);
       if($email == ""){
           $emailErrorMsg = "Please enter the email"; 
       }else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
           $emailErrorMsg = "Please enter a valid email";  
       }
       if($password == ""){
           $passwordErrorMsg = "Enter your password";
}

Once there are no validation errors, the values of the input fields will run in the SQL query. To obtain the hashed value of the password, pass the password in the md5() method.

if($emailErrorMsg == "" && $passwordErrorMsg == ""){
   $password = md5($password);
   $query = "SELECT * FROM users WHERE email = '$email' AND password='$password'";
   $find_user = mysqli_query($connection, $query);
   if(mysqli_num_rows($find_user) == 1){
       $_SESSION["email"] = $email;
       while($row = mysqli_fetch_assoc($find_user)){
           $_SESSION["username"] = $row["username"];
       }
           
       header("location:home.php");
   }else{
       $error = "Invalid credentials";
   }
}
Login form with error message

After retrieving the hashed password, pass the email and the hashed password in the SQL query and run it using the mysqli_query() method.

On obtaining the result, you need to pass it in the mysqli_num_rows() method. If mysqli_num_rows() method returns the value 1, then you can authenticate the user.

Store the email and username in the $_SESSION[] and redirect the user to the home page.

Logout the User

User authentication is done using the $_SESSION[] superglobal. To log out the user, you need to destroy the SESSION and redirect the user to login.php.

  session_start();
   $_SESSION = array();
   session_destroy();
   header("Location: login.php");
   exit;

A Secure Authentication System Is Important

You have already learned to add an authentication system using PHP and MySQL. You can take this project to the next level by adding more advanced functionalities to it or else integrate this system in a large scale project like a social media app, a blog page, or any major project. Keep learning and building new stuff as much as you can.

Want to learn more about PHP? There are many manipulations you can do with the right PHP know-how.

 

Releated

How to Work Effectively With Dates and Times in MySQL

Dates and times are important, they help keep things organized, and are an integral aspect of any software operation. Efficiently working with them within the database can sometimes seem confusing, whether it’s working across the various time zones, adding / subtracting dates, and other operations. Learn the various MySQL functions available to easily handle and […]