How to send email verification for New Users in PHP

Hello in today class we will learn how to send email verification when a new user registers. After we Created a Login Form and a Register From, now we need confirm the user email by sending an email confirmation.

 

Before we need add two more rows in our database, wich we have created in How to create a Login Form. We will use SQL Language to add this rows:

ALTER TABLE `user` ADD `active_account` INT(3) NOT NULL AFTER `password`, ADD `hash` VARCHAR(32) NOT NULL AFTER `active_account`;

 

Once that is done we need make some changes in our connection.php file. First we need to save our  hash in our database, this hash will be generated randomly. Than we send a confirmation mail using the php mail function.

(Note: all code is commented if you any doubt contact us)

Our code:

//is user isset button register_user
if (isset($_POST['register_user'])) {
  //receive all input values from the form and escape them
  $name = mysqli_real_escape_string($db, $_POST['name']);
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $email = mysqli_real_escape_string($db, $_POST['email']);
  $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
  $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
  //generate a random hash for users
  $hash = md5(rand(0,1000));

  //check if individually if all fields aren't empty
  if (empty($name)) { echo "Name Required!<br>"; }
  if (empty($username)) { echo "Username Required!<br>"; }
  if (empty($email)) { echo "Email Required!"; }
  if (empty($password_1)) { echo "Password Required!<br>"; }
  //check if all fields are not empty
  //if to continue the code
  //else print 'All field required'
  if(!empty($name) && !empty($email) && !empty($username) && !empty($password_1) &&!empty($password_2)){
      //check if passords matchs
      //if true continue doing the code
      //else print 'Two password not match'
      if ($password_1 != $password_2) {
          echo "The two passwords do not match<br>";
      }else{
          //Check if username exists in database
          $checkUsername = "SELECT username FROM users WHERE username='$username'";
          $resultCheckUsername = mysqli_query($db, $checkUsername);
          //if mysqli_num_rows is bigger then 0
          //it means that user already exists
          //and print 'Username already exists'
          if(mysqli_num_rows($resultCheckUsername)>0){
            echo "Username already exists<br>";
          }

          //Check if email exists in database
          $checkEmail = "SELECT email FROM users WHERE email='$email'";
          $resultCheckEmail = mysqli_query($db, $checkEmail);
          //if mysqli_num_rows is bigger then 0
          //it means that email already exists
          //and print 'Email already exists'
          if(mysqli_num_rows($resultCheckEmail)>0){
            echo "Email already exists<br>";
          }

          //encrypt the password before saving in the database
          $password = md5($password_1);
          //insert into database the new user information
          $query = "INSERT INTO user (name, username, email, password, hash) VALUES ('$name', '$username', '$email', '$password', '$hash')";
          mysqli_query($db, $query);
          //then redirect user to login.php

          //sp
          $url = "http://www.w7code.com";
          //send a confirmation email to user mail
          $to      = $email;
          //set this to your email that you want
          $from = "noreply@w7code.com";
          //set the email for the user need to reply
          $replyTo = "email@w7code.com";
          //you change the subject of the email
          $subject = 'Confirm Account';
          //this is the body of our email
          $message = '
          Hello '.$name.',
          Please Confirm your account:
          '.$url.'/verify_account.php?email='.$email.'&hash='.$hash.'
          ';
          //this are the headers that we have specified
          $headers = 'From: '.$from. "\r\n" .
              'Reply-To: '.$replyTo. "\r\n" .
              'X-Mailer: PHP/' . phpversion();

          //this is the php mail function that is responsible for sanding the email
          //note if the email isn't in the mail box, check spam box
          mail($to, $subject, $message, $headers);

          header('location: login.php');
      }
  }else{
    echo "All fields are required!<br>";
  }
}

 

 

Now we just need create the file that user will be redirected and he press the url in email, we will call to this file ‘ verify_account.php ‘:

?php
  session_start();
  include('connection.php');
?>
<!DOCTYPE html>
<html>
      <head>
        <title>W7code - Verify Account</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <meta name=viewport content="width=device-width, initial-scale=1">
      </head>

      <body>
          <div class="content">
            <?php
              //get email and the user hash from url and sacping them
              $email = mysqli_real_escape_string($db, $_GET['email']);
              $hash = mysqli_real_escape_string($db, $_GET['hash']);
              //select from that databse where user email and hash is equal to
              //the we have getted from url
              $query = "SELECT email, hash, active_account FROM user WHERE email='$email' AND hash='$hash' AND active_account='0'";
        			$results = mysqli_query($db, $query);
              //check if if our databse have any user with this features
              $userAccount = mysqli_num_rows($results);
            //if is true active account
            if($userAccount>0){
              //by set active_account='1' we are activing the user account
              $query = "UPDATE user SET active_account='1' WHERE email='$email' AND hash='$hash'";
              mysqli_query($db, $query);
              //message that is printed when user visit url
              echo 'Your account has been activated';

            }else{
              //send if the account already have been actived
              echo 'Your account already has been activated';
            }
             ?>
          </div>
      </body>
</html>

 

This process is almost complete, we just need to change our login settings. Because we only want that user that have active their accounts can login in. For that we just need update one line of code in ‘ connection.php ‘ to:

 

$query = "SELECT * FROM user WHERE username='$username' AND password='$password' AND active_account='1'";

 

Full code of  ‘ connection.php ‘:

<?php
session_start();
include('bd.php');

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

  //we are getting the username and password input
  //and than we are escaping the user input to avoid code input
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password']);

  //check if username field is not empty
  if (empty($username)) {
    echo "Username Required!<br>";
  }
  //check if password field is not empty
  if (empty($password)) {
    echo "Password Required!<br>";
  }

    //our password is encrypted in our database
    //so we need to encrypt the password that user inputs
    $password = md5($password);
    // * means select all
    //we are selecting the user where username and the password is
    //equal to user inputs
    $query = "SELECT * FROM user WHERE username='$username' AND password='$password' AND active_account='1'";
    //to return some result using mysqli_query
    $results = mysqli_query($db, $query);

    //count if is any table with that username and Password
    //if is true redirect usr to the user user panel
    if (mysqli_num_rows($results) > 0) {
      $row = mysqli_fetch_assoc($results);
      //we set a session named 'username' to the value of username that user have inputed
      $_SESSION['username'] = $username;
      header('Location: user_panel.php');

    //else return the user to the login form
    }else {
      echo "Password or username wrong!<br>";
    }

}

//is user isset button register_user
if (isset($_POST['register_user'])) {
  //receive all input values from the form and escape them
  $name = mysqli_real_escape_string($db, $_POST['name']);
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $email = mysqli_real_escape_string($db, $_POST['email']);
  $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
  $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
  //generate a random hash for users
  $hash = md5(rand(0,1000));

  //check if individually if all fields aren't empty
  if (empty($name)) { echo "Name Required!<br>"; }
  if (empty($username)) { echo "Username Required!<br>"; }
  if (empty($email)) { echo "Email Required!"; }
  if (empty($password_1)) { echo "Password Required!<br>"; }
  //check if all fields are not empty
  //if to continue the code
  //else print 'All field required'
  if(!empty($name) && !empty($email) && !empty($username) && !empty($password_1) &&!empty($password_2)){
      //check if passords matchs
      //if true continue doing the code
      //else print 'Two password not match'
      if ($password_1 != $password_2) {
          echo "The two passwords do not match<br>";
      }else{
          //Check if username exists in database
          $checkUsername = "SELECT username FROM users WHERE username='$username'";
          $resultCheckUsername = mysqli_query($db, $checkUsername);
          //if mysqli_num_rows is bigger then 0
          //it means that user already exists
          //and print 'Username already exists'
          if(mysqli_num_rows($resultCheckUsername)>0){
            echo "Username already exists<br>";
          }

          //Check if email exists in database
          $checkEmail = "SELECT email FROM users WHERE email='$email'";
          $resultCheckEmail = mysqli_query($db, $checkEmail);
          //if mysqli_num_rows is bigger then 0
          //it means that email already exists
          //and print 'Email already exists'
          if(mysqli_num_rows($resultCheckEmail)>0){
            echo "Email already exists<br>";
          }

          //encrypt the password before saving in the database
          $password = md5($password_1);
          //insert into database the new user information
          $query = "INSERT INTO user (name, username, email, password, hash) VALUES ('$name', '$username', '$email', '$password', '$hash')";
          mysqli_query($db, $query);
          //then redirect user to login.php

          //sp
          $url = "http://www.w7code.com";
          //send a confirmation email to user mail
          $to      = $email;
          //set this to your email that you want
          $from = "noreply@w7code.com";
          //set the email for the user need to reply
          $replyTo = "email@w7code.com";
          //you change the subject of the email
          $subject = 'Confirm Account';
          //this is the body of our email
          $message = '
          Hello '.$name.',
          Please Confirm your account:
          '.$url.'/verify_account.php?email='.$email.'&hash='.$hash.'
          ';
          //this are the headers that we have specified
          $headers = 'From: '.$from. "\r\n" .
              'Reply-To: '.$replyTo. "\r\n" .
              'X-Mailer: PHP/' . phpversion();

          //this is the php mail function that is responsible for sanding the email
          //note if the email isn't in the mail box, check spam box
          mail($to, $subject, $message, $headers);

          header('location: login.php');
      }
  }else{
    echo "All fields are required!<br>";
  }
}

 

 

Final result:

 

Download the full code here.

Do you have any doubt? If yes, please comment bellow, so we can explain them.


Leave a Reply

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