PHP Registration with Email Verification

PHP Email verification is most important because its check the email reality actually that the email is a real email or a fake email.

Email Verification: 

Normally when we create an account on any website after the account creation they want email verification, and actually, email verification is very very important. actually, they want to check your email is a real email or a fake email, so very straight forward email verification just checks your email reality.


php email verification

What we will cover in the article? 

  1. PHP Registration and login form
  2. PHP Email verification
  3. PHP Form Validation Library
  4. Object-Oriented Programming 
  5. PHPMailer library
First of all, we will create a PHP registration form with email verification and as well the login form,
and for the form validation actually, we will use the form validation library which we have already created the form validation library and another we will use object-oriented programming paradigm. we will verify the user email so for sending the email basically we will use the PHPMailer library and it's very easy to send an email.

PHPMailer library setting:

Before sending an email with PHPMailer library first we have to do some settings. by default, Gmail does not allow the third party libraries to use your account for security reason, so now we need tell to Gmail that the PHPMailer library can use our Gmail account. follow the below steps
  1. Login to your Gmail account that account you have provided in the PHPMailer library
  2. Now we have to enable the less secure app so simply click here and ON less secure app

Source Code: 

userConfirmation.sql

-- phpMyAdmin SQL Dump
-- version 4.8.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jun 21, 2019 at 04:39 AM
-- Server version: 10.1.34-MariaDB
-- PHP Version: 7.2.7

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `userconfirmation`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `fullName` varchar(100) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `code` varchar(255) NOT NULL,
  `status` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `fullName`, `email`, `password`, `code`, `status`) VALUES
(1, 'shakil khan', 'shakilkhan@gmail.com', '12345678', 'sfsdfdsf', 0),
(20, 'shakil khan', 'shakilkhanblogger@gmail.com', '$2y$10$P/s435TUM9zeofSdfZ94.eSaK.WVGpp4KRM4dO8d2xMLmGxHGDQfq', '$2y$10$efJWVRxTC5A.DlERSSqKMeQqO6/iyWW9ULz88ea0AXLC4pVXy9G3q', 1);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

assets/css/style.css


body {
    background: url("../img/bg.jpg") no-repeat;
    background-size: cover;
    background-color: rgba(0,0,0,.8);
    background-blend-mode: overlay;
}

.card {
    border-radius: 0!important;
}

.error {
    color: red;
}

.jumb {
    height: calc(100vh - 65px);
}

classes/db.php


<?php

class db {

    public $connect;
    public function __construct()
    {
        try {

            $this->connect = new PDO("mysql:host=localhost;dbname=userConfirmation", 'root', '');

        } catch(PDOException $e){
            echo "Connection error: ". $e->getMessage();
        }
    }

}


?>

classes/queries.php


<?php

class queries extends db {

    public $result;

    // CRUD Method
    public function query($qry, $params = []){

    if(empty($params)){
        $this->result = $this->connect->prepare($qry);
        return $this->result->execute();
    } else {
        $this->result = $this->connect->prepare($qry);
        return $this->result->execute($params);
    }

    }

    // Count the number of rows
    public function count(){
        return $this->result->rowCount();
    }

    // fetch a single row
    public function fetch(){
        return $this->result->fetch(PDO::FETCH_OBJ);
    }

}


?>

classes/sendEmail.php


<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
 class sendEmail {

    public function send($userName, $email, $url){

       // Load Composer's autoloader
require 'phpmailer/vendor/autoload.php';

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 0;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'emailsenderudemy@gmail.com';                     // SMTP username
    $mail->Password   = 'your password';                               // SMTP password
    $mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('emailsenderudemy@gmail.com', 'shakil khan team');
    $mail->addAddress($email, $userName);     // Add a recipient

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Confirm your email';
    $mail->Body    = '<p> Hi ' . $userName . ' please confirm your email click on the below link</p> <p><a href="'. $url .'">Confirm email</a></p><p> OR copy an paste this link '. $url .'</p>';
    $mail->AltBody = '<p> Hi ' . $userName . ' please confirm your email click on the below link</p> <p><a href="'. $url .'">Confirm email</a></p><p> OR copy an paste this link '. $url .'</p>';

    $mail->send();
    return true;
} catch (Exception $e) {
    return false;
}

    }

 }


?>

classes/validation.php


<?php
error_reporting(0);
class validation extends db {

    public $errors = [];

    public function input($field){
        if($_SERVER['REQUEST_METHOD'] == 'POST' || $_SERVER['REQUEST_METHOD'] == 'post'){
            return strip_tags(trim($_POST[$field]));
        } else if($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'get'){
            return strip_tags(trim($_GET[$field]));
        }
    }
    public function validate($field, $label, $rules){

    //    Split rule string on pipe sign
    $allRules = explode("|", $rules);
    $inputField = $this->input($field);
    // Check required rule in the array
    if(in_array("required", $allRules)){
        
        if(empty($inputField)){
            return $this->errors[$field] = $label . " is required";
        }

    }
    // Close required rule

    // Check uniqueEmail rule in the array
    if(in_array('uniqueEmail', $allRules)){

        $uniqueIndex = array_search("uniqueEmail", $allRules);
        $tableIndex  = $uniqueIndex + 1;
        $tableName   = $allRules[$tableIndex];
        $result = $this->connect->prepare(" SELECT * FROM " . $tableName . " WHERE " . $field . " = ? ");
        if($result->execute([$inputField])){
            if($result->rowCount() > 0 ){
                return $this->errors[$field] = $label . " is already exist";
            }
        }

    }
    // Close uniqueEmail rule

    // Check min_len rule in the array
    if(in_array("min_len", $allRules)){
        $minLenIndex = array_search("min_len", $allRules);
        $valueIndex = $minLenIndex + 1;
        $minValue = $allRules[$valueIndex];
        if(strlen($inputField) < $minValue){
            return $this->errors[$field] = $label . " is too short";
        }

    }

    }

    public function run(){
        if(empty($this->errors)){
            return true;
        } else {
            return false;
        }
    }

}

?>

classes/verify.php


<?php

class verify extends queries {

  public function emailVerify(){

    if(isset($_GET['confirmation'])){
        $code = $_GET['confirmation'];
        $status = 1;
        if($this->query("SELECT * FROM users WHERE code = ? ", [$code])){
            if($this->count() == 1){

                $row = $this->fetch();
                $userId = $row->id;
                if($this->query("UPDATE users SET status = ? WHERE id = ? ", [$status, $userId])){

                    $_SESSION['emailVerified'] = "Your account has been verified successfully please login";
                    header("location:login.php");

                }

            }
        }
    }

  }

}


?>

inc.php


<?php
session_start();
spl_autoload_register(function($className){

    include "classes/$className.php";

});



?>

components/styles.php


<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="assets/css/style.css">

components/nav.php


<nav class="navbar navbar-expand-lg navbar-dark bg-primary" style="background: #7B68EE!important;">
    <div class="container">
  <a class="navbar-brand" href="#">CMS</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarColor01">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="index.php">Home <span class="sr-only">(current)</span></a>
      </li>
      <?php if(isset($_SESSION['userId'])): ?>
      <li class="nav-item active">
        <a class="nav-link" href="logout.php">logout</a>
      </li>
<?php else: ?>
<li class="nav-item active">
        <a class="nav-link" href="index.php">Register</a>
      </li>
      <li class="nav-item active">
        <a class="nav-link" href="login.php">Login</a>
      </li>
<?php endif; ?>
     
    </ul>
  </div>
    </div>
</nav>

index.php


<?php
include "inc.php";
if(isset($_SESSION['userId'])): 

  header("location: profile.php");
  
  endif;
$validation = new validation;
$queries    = new queries;
$sendEmail  = new sendEmail;

if(isset($_POST['register'])){

  $validation->validate('fullName', 'full name', 'required');
  $validation->validate('email', 'Email', 'uniqueEmail|users|required');
  $validation->validate('password', 'Password', 'required|min_len|6');

  if($validation->run()){

     $fullName = $validation->input('fullName');
     $email    = $validation->input('email');
     $password = $validation->input('password');
     $password = password_hash($password, PASSWORD_DEFAULT);
     $code     = rand();
     $code     = password_hash($code, PASSWORD_DEFAULT);
     $url      = "http://" . $_SERVER['SERVER_NAME'] . "/emailConfirmation/confirm.php?confirmation=" . $code;
     $status   = 0;
     if($queries->query("INSERT INTO users (fullName, email, password, code, status) VALUES (?,?,?,?,?) ", [$fullName, $email, $password, $code, $status])){

      if($sendEmail->send($fullName, $email, $url)){
        
        $_SESSION['accountCreated'] = "Your account has been created successfully please verify your email";
        header("location: login.php");

      }

     }
    
     
  }

}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Registration Form</title>
    <?php include "components/styles.php"; ?>
</head>
<body>
  <?php include "components/nav.php"; ?> 
  <div class="container">
  <div class="row mt-5">
  <div class="col-md-5">
  <div class="card">
  <div class="card-body">
  <form action="" method="POST">
  <div class="form-group">
  <h3>Registration Form</h3>
  </div>
  <!-- Close form-group -->
  <div class="form-group">
  <input type="text" name="fullName" class="form-control" placeholder="Enter Full Name" value="<?php if($validation->input('fullName')): echo $validation->input('fullName'); endif; ?>">
  <div class="error">
    <?php if(!empty($validation->errors['fullName'])): echo $validation->errors['fullName']; endif; ?>
  </div>
  </div>
  <!-- Close form-group -->

  <div class="form-group">
  <input type="email" name="email" class="form-control" placeholder="Enter Email" value="<?php if($validation->input('email')): echo $validation->input('email'); endif; ?>" >
  <div class="error">
  <?php if(!empty($validation->errors['email'])): echo $validation->errors['email']; endif; ?>
  </div>
  </div>
  <!-- Close form-group -->

  <div class="form-group">
  <input type="password" name="password" class="form-control" placeholder="Create new password" value="<?php if($validation->input('passwors')): echo $validation->input('password'); endif; ?>">
  <div class="error">
  <?php if(!empty($validation->errors['password'])): echo $validation->errors['password']; endif; ?>
  </div>
  </div>
  <!-- Close form-group -->

  <div class="form-group">
  <input type="submit" name="register" class="btn btn-info" value="Register &rarr;" style="background: #7B68EE!important;">
  </div>
  <!-- Close form-group -->
  </form>
  <!-- Close form -->
  </div>
  <!-- Close card-body -->
  </div>
  <!-- Close card -->
  </div>
  <!-- Close col-md-5 -->
  <div class="col-md-5 text-white ml-auto">
   <h1>Registration Form</h1><hr>
   <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum adipisci tempora sit voluptas inventore illum aliquam quod, incidunt quas dolorem modi hic earum est quidem molestias optio repellat id ipsum.</p>
  </div>
  <!-- Close col-md-5 -->
  </div>
  <!-- Close row -->
  </div>
   <!-- Close container -->
</body>
</html>

login.php


<?php
include "inc.php";
if(isset($_SESSION['userId'])): 

  header("location: profile.php");
  
  endif; 
$validation = new validation;
$queries    = new queries;

if(isset($_POST['login'])){

  $validation->validate('email', 'Email', 'required');
  $validation->validate("password", 'Password', 'required');
  if($validation->run()){
    
    $email = $validation->input('email');
    $password = $validation->input('password');
    if($queries->query("SELECT * FROM users WHERE email = ? ", [$email])){
      if($queries->count() > 0 ){
        $row = $queries->fetch();
        $userId = $row->id;
        $userName = $row->fullName;
        $dbPassword = $row->password;
        $status     = $row->status;
        if($status == 0){

          $_SESSION['notVerified'] = "Please verify your email and try again";

        } else {
       if(password_verify($password, $dbPassword)){

        $_SESSION['userId'] = $userId;
        $_SESSION['userName'] = $userName;
        header("location: profile.php");

       } else {
         $validation->errors['password'] = "Sorry invalid password";
       }
      }

      } else {
        $validation->errors['email'] = "Sorry invalid email";
      }
    }

  }

}


?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Login Form</title>
    <?php include "components/styles.php"; ?>
</head>
<body>
  <?php include "components/nav.php"; ?> 
  <div class="container">
  <div class="row mt-5">
  <div class="col-md-5">
    <?php if(isset($_SESSION['accountCreated'])): ?>
      <div class="alert alert-success">
        <?php echo $_SESSION['accountCreated']; ?>
      </div>
<?php endif; ?>
<?php unset($_SESSION['accountCreated']); ?>

<!-- User account has been verified successfully -->
<?php if(isset($_SESSION['emailVerified'])): ?>
      <div class="alert alert-success">
        <?php echo $_SESSION['emailVerified']; ?>
      </div>
<?php endif; ?>
<?php unset($_SESSION['emailVerified']); ?>


<?php if(isset($_SESSION['notVerified'])): ?>
      <div class="alert alert-danger">
        <?php echo $_SESSION['notVerified']; ?>
      </div>
<?php endif; ?>
<?php unset($_SESSION['notVerified']); ?>
  <div class="card">
  <div class="card-body">
  <form action="" method="POST">
  <div class="form-group">
  <h3>Login Form</h3>
  </div>
  <!-- Close form-group -->
  <div class="form-group">
  <input type="email" name="email" class="form-control" placeholder="Enter Email" value="<?php if($validation->input('email')): echo $validation->input('email'); endif; ?>">
  <div class="error">
  <?php if(!empty($validation->errors['email'])): echo $validation->errors['email']; endif; ?>
  </div>
  </div>
  <!-- Close form-group -->

  <div class="form-group">
  <input type="password" name="password" class="form-control" placeholder="Create new password">
  <div class="error">
  <?php if(!empty($validation->errors['password'])): echo $validation->errors['password']; endif; ?>
  </div>
  </div>
  <!-- Close form-group -->

  <div class="form-group">
  <input type="submit" name="login" class="btn btn-info" value="Login &rarr;" style="background: #7B68EE!important;">
  </div>
  <!-- Close form-group -->
  </form>
  <!-- Close form -->
  </div>
  <!-- Close card-body -->
  </div>
  <!-- Close card -->
  </div>
  <!-- Close col-md-5 -->
  <div class="col-md-5 text-white ml-auto">
   <h1>Login Form</h1><hr>
   <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum adipisci tempora sit voluptas inventore illum aliquam quod, incidunt quas dolorem modi hic earum est quidem molestias optio repellat id ipsum.</p>
  </div>
  <!-- Close col-md-5 -->
  </div>
  <!-- Close row -->
  </div>
   <!-- Close container -->
</body>
</html>

verify.php


<?php
include "inc.php";
$verify = new verify;
$verify->emailVerify();


?>

profile.php


<?php include "inc.php"; ?>
<?php if(!isset($_SESSION['userId'])): 

header("location: login.php");

endif; ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Profile</title>
    <?php include "components/styles.php" ?>
</head>
<body>
   <?php include "components/nav.php"; ?>
   
   <div class="jumbotron jumb">
       <h1>Hello . <?php echo $_SESSION['userName']; ?></h1>
   </div>
   
</body>
</html>

logout.php


<?php 

session_start();
session_destroy();
header("location:login.php");


?>

Download the full source code:

To download the full source code just click on the below download link.

COMMENTS

BLOGGER: 1
Loading...
Name

ajax,2,HTML & CSS,19,JavaScript,1,PHP,11,
ltr
item
webtipstricks: PHP Registration with Email Verification
PHP Registration with Email Verification
PHP Email verification is most important because its check the email reality actually that the email is a real email or a fake email.
https://i.ytimg.com/vi/videoseries/hqdefault.jpg
https://i.ytimg.com/vi/videoseries/default.jpg
webtipstricks
https://www.webtipstricks.com/2019/06/php-email-verification.html
https://www.webtipstricks.com/
https://www.webtipstricks.com/
https://www.webtipstricks.com/2019/06/php-email-verification.html
true
4027471107773963481
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy