• Latest
  • Trending
Add Authentication to Any PHP App Using MySQL

Add Authentication to Any PHP App Using MySQL

February 28, 2022
Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023
Vice President Dr. Bawumia inaugurates  ICT Hub

Vice President Dr. Bawumia inaugurates ICT Hub

April 2, 2023
Co-Creation Hub’s edtech accelerator puts $15M towards African startups

Co-Creation Hub’s edtech accelerator puts $15M towards African startups

February 20, 2023
Data Leak Hits Thousands of NHS Workers

Data Leak Hits Thousands of NHS Workers

February 20, 2023
EU Cybersecurity Agency Warns Against Chinese APTs

EU Cybersecurity Agency Warns Against Chinese APTs

February 20, 2023
How Your Storage System Will Still Be Viable in 5 Years’ Time?

How Your Storage System Will Still Be Viable in 5 Years’ Time?

February 20, 2023
The Broken Promises From Cybersecurity Vendors

Cloud Infrastructure Used By WIP26 For Espionage Attacks on Telcos

February 20, 2023
Instagram and Facebook to get paid-for verification

Instagram and Facebook to get paid-for verification

February 20, 2023
YouTube CEO Susan Wojcicki steps down after nine years

YouTube CEO Susan Wojcicki steps down after nine years

February 20, 2023
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Friday, 17 July, 2026
  • Login
itechnewsonline.com
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion
Subscription
Advertise
No Result
View All Result
itechnewsonline.com
No Result
View All Result

Add Authentication to Any PHP App Using MySQL

Explore the power of PHP and MySQL with this tutorial that guides you through creating authentication on your web app.

by ITECHNEWS
February 28, 2022
in Data Science, Leading Stories
0 0
0
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.

YOU MAY ALSO LIKE

French Telco Orange Hit by Cyber-Attack

ATC Ghana supports Girls-In-ICT Program

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.phpfile.

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.

Source: UNNATI BAMANIA
Via: makeuseof
Tags: Add Authentication to Any PHP App Using MySQL
ShareTweet

Get real time update about this post categories directly on your device, subscribe now.

Unsubscribe

Search

No Result
View All Result

Recent News

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025

Recent News

  • Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa July 29, 2025
  • French Telco Orange Hit by Cyber-Attack July 29, 2025
  • ATC Ghana supports Girls-In-ICT Program April 25, 2023
  • Vice President Dr. Bawumia inaugurates ICT Hub April 2, 2023
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In

Add New Playlist

No Result
View All Result
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
Go to mobile version