PHP and MySQL User Registration with Email Verification

To email verification in PHP + MySQL; In this tutorial, i am going to show you how to create user registration with email verification in PHP + MySQL. and how to send email using gmail smtp server in PHP.

Send email verification link from registration form in PHP and MySQL tutorial, i will create simple user registration form and then submit form with data to store & send email verification link with code. After that, when you click on email verification link, you will be verified from database with gmail smtp detail.

User Registration with Email Verification using PHP and MySQL

Follow below following steps to verify/activate user account by email link in PHP and MySQL after registration:

  • Step 1 – Create PHP Project
  • Step 2 – Create Database Table And Connect App to DB
  • Step 3 – Create Registration HTML Form
  • Step 4 – Send Email With Verification Code Link
  • Step 5 – Create Email Verification PHP File

Step 1 – Create PHP Project

In step 1, Navigate to your local web server directory. And inside this directory, create one directory. And you can name this folder anything.

Here, I will “demo” the name of this folder. Then open this folder in any text editor (i will use sublime text editor).

Step 2 – Create Database Table And Connect App to DB

In step 2, you need to create database and table. So run the following sql query to create database and table:

CREATE DATABASE my_db;

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(250) NOT NULL,
  `status` int(11) NOT NULL DEFAULT '0',
  `email_verification_link` varchar(255) NOT NULL,
  `email_verified_at` TIMESTAMP NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Then create a php file that named mydbCon. Which is used to connect phpmyadmin mysql database to project (demo).

So, now create mydbCon file and add the below given code into your file:

<?php

    $hName='localhost'; // host name

    $uName='root';   // database user name

    $password='';   // database password

    $dbName = "my_db"; // database name

    $conn= mysqli_connect($hName,$uName,$password,"$dbName");

      if(!$conn){
          die('Could not Connect MySql Server:' .mysql_error());
      }
?>

Step 3 – Create Registration HTML Form

In step 3, create a php file that named index.php. This file will display PHP simple form and store form data into MySQL database with validation. Now, you need to add the following simple form code into index.php file:

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
      <title>User Registration with Email Verification in PHP + MySQL - Laratutorials.com</title>
       <!-- CSS -->
       <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
   </head>
   <body>
      <div class="container mt-5">
          <div class="card">
            <div class="card-header text-center">
              User Registration with Email Verification in PHP + MySQL - Laratutorials.COM
            </div>
            <div class="card-body">
              <form action="send-email.php" method="post">

                <div class="form-group">
                  <label for="exampleInputEmail1">Name</label>
                  <input type="text" name="name" class="form-control" id="name" required="">
                </div>                                

                <div class="form-group">
                  <label for="exampleInputEmail1">Email address</label>
                  <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp" required="">
                  <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
                </div>

                <div class="form-group">
                  <label for="exampleInputEmail1">Password</label>
                  <input type="password" name="password" class="form-control" id="password" required="">
                </div>                   

                <div class="form-group">
                  <label for="exampleInputEmail1">Confirm Password</label>
                  <input type="password" name="cpassword" class="form-control" id="cpassword" required="">
                </div>   

                <input type="submit" name="password-reset-token" class="btn btn-primary">
              </form>
            </div>
          </div>
      </div>

   </body>
</html>

Step 4 – Send Email With Verification Code Link

In step 4, create one php file, which name send-email.php. And add the following code into it:

<?php
if(isset($_POST['password-reset-token']) && $_POST['email'])
{
    include "mydbCon.php";

    $result = mysqli_query($conn,"SELECT * FROM users WHERE email='" . $_POST['email'] . "'");

    $row= mysqli_num_rows($result);

    if($row < 0)
    {
      
       $token = md5($_POST['email']).rand(10,9999);

       mysqli_query($conn, "INSERT INTO users(name, email, email_verification_link ,password) VALUES('" . $_POST['name'] . "', '" . $_POST['email'] . "', '" . $token . "', '" . md5($_POST['password']) . "')");

        $link = "<a href='localhost/demo/verify-email.php?key=".$_POST['email']."&token=".$token."'>Click and Verify Email</a>";

        require_once('phpmail/PHPMailerAutoload.php');

        $mail = new PHPMailer();

        $mail->CharSet =  "utf-8";
        $mail->IsSMTP();
        // enable SMTP authentication
        $mail->SMTPAuth = true;                  
        // GMAIL username
        $mail->Username = "[email protected]";
        // GMAIL password
        $mail->Password = "your_gmail_password";
        $mail->SMTPSecure = "ssl";  
        // sets GMAIL as the SMTP server
        $mail->Host = "smtp.gmail.com";
        // set the SMTP port for the GMAIL server
        $mail->Port = "465";
        $mail->From='[email protected]';
        $mail->FromName='your_name';
        $mail->AddAddress('reciever_email_id', 'reciever_name');
        $mail->Subject  =  'Reset Password';
        $mail->IsHTML(true);
        $mail->Body    = 'Click On This Link to Verify Email '.$link.'';
        if($mail->Send())
        {
          echo "Check Your Email box and Click on the email verification link.";
        }
        else
        {
          echo "Mail Error - >".$mail->ErrorInfo;
        }
    }
    else
    {
      echo "You have already registered with us. Check Your email box and verify email.";
    }
}
?>

The send-email.php file code will store user registration form data into MySQL database and send email verification link. And Add the smtp details in send-email.php file.

Step 5 – Create Email Verification PHP File

In step 5, create one php file, which name verify-email.php. And add the following code into it:

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
      <title>User Account Activation by Email Verification using PHP</title>
       <!-- CSS -->
       <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
   </head>
   <body>
          <?php
            if($_GET['key'] && $_GET['token'])
            {
              include "mydbCon.php";
              
              $email = $_GET['key'];

              $token = $_GET['token'];

              $query = mysqli_query($conn,
              "SELECT * FROM `users` WHERE `email_verification_link`='".$token."' and `email`='".$email."';"
              );

              $d = date('Y-m-d H:i:s');

                if (mysqli_num_rows($query) > 0) {
                   
                  $row= mysqli_fetch_array($query);

                   if($row['email_verified_at'] == NULL){

                     mysqli_query($conn,"UPDATE users set email_verified_at ='" . $d . "' WHERE email='" . $email . "'");
                     $msg = "Congratulations! Your email has been verified.";
                   }else{

                      $msg = "You have already verified your account with us";
                   }
     
                } else {

                  $msg = "This email has been not registered with us";
                }

              }
              else
              {
              $msg = "Danger! Your something goes to wrong.";
            }
            ?>
      <div class="container mt-3">
          <div class="card">
            <div class="card-header text-center">
              User Account Activation by Email Verification using PHP
            </div>
            <div class="card-body">
             <p><?php echo $msg; ?></p>
            </div>
          </div>
      </div>

   </body>
</html>

The verify-email.php file code will verify user email from mysql database.

Conclusion

To email verification in PHP + MySQL; Through this tutorial, you have learned how to send email verification link with user registration form in PHP + MySQL using gmail smtp details.

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *