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

Add Authentication to Any PHP App Using MySQL

February 28, 2022
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
Instagram fined €405m over children’s data privacy

Instagram fined €405m over children’s data privacy

September 6, 2022
8 Most Common Causes of a Data Breach

5.7bn data entries found exposed on Chinese VPN

August 18, 2022
Fibre optic interconnection linking Cameroon and Congo now operational

Fibre optic interconnection linking Cameroon and Congo now operational

July 15, 2022
Ericsson and MTN Rwandacell Discuss their Long-Term Partnership

Ericsson and MTN Rwandacell Discuss their Long-Term Partnership

July 15, 2022
Airtel Africa Purchases $42M Worth of Additional Spectrum

Airtel Africa Purchases $42M Worth of Additional Spectrum

July 15, 2022
Huawei steps up drive for Kenyan talent

Huawei steps up drive for Kenyan talent

July 15, 2022
TSMC predicts Q3 revenue boost thanks to increased iPhone 13 demand

TSMC predicts Q3 revenue boost thanks to increased iPhone 13 demand

July 15, 2022
Facebook to allow up to five profiles tied to one account

Facebook to allow up to five profiles tied to one account

July 15, 2022
Top 10 apps built and managed in Ghana

Top 10 apps built and managed in Ghana

July 15, 2022
MTN Group to Host the 2nd Edition of the MoMo API Hackathon

MTN Group to Host the 2nd Edition of the MoMo API Hackathon

July 15, 2022
KIOXIA Introduce JEDEC XFM Removable Storage with PCIe/NVMe Spec

KIOXIA Introduce JEDEC XFM Removable Storage with PCIe/NVMe Spec

July 15, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Sunday, 5 February, 2023
  • 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

Inaugural AfCFTA Conference on Women and Youth in Trade

Instagram fined €405m over children’s data privacy

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
ShareTweetShare
Plugin Install : Subscribe Push Notification need OneSignal plugin to be installed.

Search

No Result
View All Result

Recent News

Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
Instagram fined €405m over children’s data privacy

Instagram fined €405m over children’s data privacy

September 6, 2022
8 Most Common Causes of a Data Breach

5.7bn data entries found exposed on Chinese VPN

August 18, 2022

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
Instagram fined €405m over children’s data privacy

Instagram fined €405m over children’s data privacy

September 6, 2022

Recent News

  • Inaugural AfCFTA Conference on Women and Youth in Trade September 6, 2022
  • Instagram fined €405m over children’s data privacy September 6, 2022
  • 5.7bn data entries found exposed on Chinese VPN August 18, 2022
  • Fibre optic interconnection linking Cameroon and Congo now operational July 15, 2022
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© 2021-2022 iTechNewsOnline.Com - Powered by BackUPDataSystems

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

© 2021-2022 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
Go to mobile version