Dj Techblog

A blog on web development

Generate OTP and store it into session variable for further use / no use of database

Last modified on Feb 14, 2021
store otp in session variable no use of database

OTP without database

OTP that is one time password is one of the important concept in user verification, either via Email or SMS. Both need otp to verify the user email or mobile number. Generating otp and storing it into database is a bad idea. There is no need to involve database in such cases where we can do the same thing without the database. Yes we can do it with seession variable which will be much easier than the involving database.

Recommended read,

Know all about php session

So, here I will show only the back end to generate otp, store it into php session variable, pass it to user email-id or mobile number. After we send the otp to respective platform we also send a verification form verification-form.php where user will enter the received otp. The entered otp will be send back to the server again to match both the otp that is, one which is stored in the session variable and another which is entered by the user. At this point of time we unset the php session variable which we have created. Because it has served its purpose, we no longer need the session variable.
Now, if both the otp matches user email or mobile number verification complete.

    $email = $_POST['email'];  // receive the email from front end
    $otp = rand(100000, 999999); //generates random otp
    $_SESSION['session_otp'] = $otp;  // stores the otp into a session variable
    $message = "Your one time email verification code is" . $otp;  //embed the otp into message.
    $sub = "Email verification from Dj Techblog";
    $headers = "From : " . "";
        $retval = mail($email,$sub,$message);
                catch(Exception $e)
                    die('Error: '.$e->getMessage());

As we can see, we dont use the database here for storing otp. rather we use php session variable to store the otp. If you want the front end code where user enter his mobile number or email. Then follow below articles.

Email verification in php using otp

Mobile number verification in php using sms otp

If you like this article, share with your friends. It will inspire me to write more.

Published on Feb 14, 2021


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



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