Dj Techblog

A blog on web development

One time url in php for Email verification

Last modified on Feb 4, 2021
Generating One time url for email verification
A one time url is a temporary link so designed that it can be used only once. It is used for variety of purposes like email verification link, one time download link, reset forgot password link etc.

Here we will talk about email verification by generating one-time urls. We can also put an expiry time limit on the validity of url, setting it to expire after 24 hours or more as per our needs.

Read,

How to generate one time url in php?

We will use some php function to generate a secured token and embed that token into url and send it to email id as an email verification link. Next we push that token into the database for user verification later. On receiving the url if the user clicks on that sent link, we will retrieve the token from the url and match it with the stored token in the database. If a match is found user is verified and we delete that token from the database to escape misusing it again.

We will use uniqid() function in php to generate a unique id based on the randomly generated username.
uniqid($username, true);

This will generate a random unique id based on username and current time in microseconds. If security is not a issue for our website we can use this function to generate a token and send it with the url as one time email verification link.

But if we are more concerned about security issue we can use an additional php function sha1() or md5() to generate cryptographically secured token. Sha1() is more secured than md5() but slower in comparison to md5(). So in high security applications use sha1() only.
Sha1(uniqid($username, true));


Here are the steps.

  1. Get user Email id to send one time url as email verification link
  2. Check for valid email id and request server to generate one time url
  3. Server generates token, stores it in database and forwards the generated link to the email id.
  4. User when visits the link gets verified. Now delete the token from database.

Get Email id to send one time url


The user enters his email id to receive otp. A script has been written to check for invalid email id which returns an error on entering an invalid email id.

Landing page : index.php

<!DOCTYPE html>
<html>
<head>
<title>Email verification using one time url in php</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

</head>
<body>

<div class="container w3-card">
  <div class="err"></div>
  <form id="mobile-number-verification">
    <div class="mobile-heading">Email Verification using one time url in php</div>
    <div class="mobile-row">
      <input type="text" id="name" class="mobile-input" placeholder="Enter your name">
      <br>
      <div id="message1"></div>
      <br>
      <input type="email" id="email" class="mobile-input" placeholder="Enter your email-id">
      <div id="message2"></div>
    </div>
    <div id="loading-image"><img src="/image/ajax-loader.gif" alt="ajax loader"></div>
    <input type="button" class="mobileSubmit" id="enter" disabled="true" value="Verify Email" onClick="generateUrl();">
  </form>
  <script>
      $('#email').on('keyup',function(){
                var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
                var email = $("#email").val();
                if(email.match(mailformat)){
                    $('#message2').html('valid').css('color','green');
                    $("#enter").prop('disabled',false);
                }
                else
                    $('#message2').html('Invalid Email').css('color','red');
                    
            }
            );
  </script>
</div>
</body>
</html>

email verification in php using otp

Makes an ajax request to the server for one time url generation

script.js

function generateUrl() {
$(".err").html("").hide();
var email = $("#email").val();
var name = $("#name").val();	
if(name.length !== 0)
{
    var input ={
        "name" : name,
        "email" : email,
        "action" : "generate_url"
    }
    $("#loading-image").show();
    $.ajax({
        
        url : 'controller.php',
        type : 'POST',
        dataType : 'json',
        data : input,
        success : function(response)
        {
            $(".container").html(response.message);
        },
        complete : function()
        {
            $("#loading-image").hide();
        },
        error : function()
        {
            $(".container").html("Error");
        }
        
    });
}
else
    $("#message1").html("Enter your name").css('color','red');

}

Server generates token, saves it in database, embeds it in url and forwards it to user email id

The server generates a unique token using the email id of the user and stores the token in the database. After that, it creates a unique one-time link embedding the token in the url and forwards the link to the user email id calling php mail() function.

controller.php

<?php

error_reporting(E_ALL & ~ E_NOTICE);

class Controller
{
  function __construct() {
      $this->processEmailVerification();
  }
  function processEmailVerification()
  {
      switch ($_POST["action"]) {
          
          case "generate_url":
              $email = $_POST['email'];
              $token = sha1(uniqid($email,true)); // this will generate unique 40 character long secured token
              $db = mysqli_connect('localhost', 'username', '(password)', 'database name');
              //here check for email id ia already registered or not
              $query = "INSERT INTO new_pending_users (email,token) VALUES ('$email','$token')";
              $result = mysqli_query($db, $query);
              if ($result === FALSE) 
              {
                  die(mysqli_error());
                   exit();
              }
              else{
                      $url = "https://djtechblog.com/php/projects/one-time-url/user-verification.php?token=$token";// send this url to user via email
                      $message = "Thankyou for registraion. kindly go to this " . $url . " to validate your email id.";
                      $sub = "Activate your account";
                      $headers = "MIME-Version: 1.0" . "\r\n";
                      $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                      $headers .= 'From: Dj Techblog <dj@djtechblog.com>' . "\r\n";
                      $retval = mail($email,$sub,$message,$headers);
                      if($retval = true)
                          echo json_encode(array( "type" =>"success", "message" => "Verification link sent to email id"));
                      else
                          echo json_encode(array( "type" =>"error", "message" => "Error"));
              }
            break;
      }   
  }
}
$controller = new Controller();
?>
                          

User verifies the email id visiting the email verification link

Now we assume that the user receives the email verification link and uses that link to verify his email id. This time server retrieves the token from the url and matches it with the token stored in the database, if match found email id verified otherwise server discards the token as an invalid or expired token. If the user is verified successfully we also delete the token so that it cant be reused again.

user-verification.php

<?php

// retrieve token
if (isset($_GET["token"]) && preg_match('/^[0-9A-F]{40}$/i', $_GET["token"])) {
  $token = $_GET["token"];
}
else {
  throw new Exception("Valid token not provided.");
}

$db = mysqli_connect('localhost', 'usrname', '(password)', 'database');
$query = "SELECT * FROM new_pending_users WHERE token='$token' LIMIT 1";

$result =  mysqli_query($db, $query);
if ($result === FALSE) {
 die(mysqli_error($connect));
}
$user = mysqli_fetch_assoc($result);
if($user)
{
 
  if ($user['token'] === $token) 
  {
              // delete token so it can't be used again
              $db0 = mysqli_connect('localhost', 'username', '(password)', 'dtabase');
          $query0 = "DELETE FROM new_pending_users WHERE token='$token' LIMIT 1";
          $result0 =  mysqli_query($db0, $query0);
          if($result0 === TRUE){
              // do one-time action here, like activating a user account
                  //  or deleting the record from new_pending_users and creating a new record in registered_users.
            echo "Email verification successful";
          }
          else
            exit;
  }
}

?>


Download the style.css file from here.

If you face any issue while implementing the code, you can contact me. Thanks for patient reading.

Ad section

Intro

Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us

Subscribe

Tags

Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section
×

Subscribe to get email notification about our new post

Name

Email

We neither sell nor share your personal information with any third party. Your identity is safe with us.