OTP using PHP – the one time passwords

OTP using PHP – the one time passwords

OTP or one time passwords are very popular on transaction websites. This technique has especially become very useful in validating users and authentication in real time.

OTP is highly used nowadays and has the following features in terms of technical usage –

  1. Transaction authentication in real time
  2. Validation checks for emails or phone numbers
  3. Password resets or confidential profile information resets
  4. Powerful anti-spam method (less prone to hijack)

Real time transaction using OTPs

Real time bank and monetary transactions are done with the help OTPs because passwords for an account can be hijacked. People often tend to share or even become very casual about the privacy of their passwords. For casual accounts like social networking websites, this practice is okay. But, just imagine, if your bank account password is with someone else and your account suddenly transfers half of your fortune to another account. What would be your reaction?

This is the reason financial websites use an OTP instant validation to check whether the actual owner is making the move. They send the one time password to a pre-registered mobile number or email id. So, if the owner is actually doing it, then the transaction goes forward otherwise it gets stopped at this stage itself.

Similarly, for password resets or confidential account information resets, OTP usage can be helpful in proper validation checks.

OTP for email and phone validation

One time passwords serve as a very good method of user authentication. Several websites offer confirmation mails to authenticate new user registrations. This is very important because it helps the website to defend against spam registrations.

Confirmation emails contain a quick reply URL. These URLs are valid for a specific period of time after which they become inactive. Within this time, the user must visit the confirmation link to prove the validity of the email id provided.

This mechanism has two benefits –

  1. The email id is validated as real. Because sometimes spam bots may generate fake email ids.
  2. The user is validated as a human and not a computer spam.

Confirmation emails contain URLs. We can replace these URLs with an OTP. An OTP is not always unique but last only for a session or a cookie with a small time span. So, there’s no fear of duplicity or anything of that sort. Even if two OTPs are same, it doesn’t matter because the validation takes place as a string match. This way email ids can be verified quickly aborting the use of validation URLs.

The user also gets verified because for a spam or robot to track a mail body string is tough and practically impossible. Moreover, if done through phone SMS OTP tracking becomes quite impossible for a hacker.


How do we implement OTP programmatically?

We are using PHP to create our OTP facility. In this tutorial, we will discuss a simple PHP session where we implement the creation of a OTP, and then moving on to the next step, the next PHP page we check whether the use has entered the correct OTP or not.

We will implement emailing a one-time password. For SMS OTPs you might choose your own mechanism. The whole procedure shall be same in that case; just the OTP sending procedure would be different.

Our PHP code for creating and sending the OTP –

//Sending mail
$subject = 'One time password for login';
$str = '';
    $str = $str.chr(rand(97,122)); 

    /*  The above line concatenates one character at a time for
        seven iterations within the ASCII range mentioned.
        So, we get a seven characters random OTP comprising of
        all small alphabets. 
$body = 'Your one time password is : '.$str;
$headers .= 'From: '.$from. "\r\n" .
   'Reply-To: '.$from. "\r\n";

mail($to, $subject, $body, $headers);

$_SESSION['loggedinuser'] = 1;
$_SESSION['secretpassword'] = $str;

In the above code, we do the following –

  1. Create an OTP using string concatenation and generating random characters using the PHP rand function within a range of ASCII values.

This range for the rand method depends on you. You can implement numbers, characters, special characters, etc. to make your OTP even more unique.

  1. Saving the OTP into a session variable (you may use cookies as well) for checking in the next step.

In our next step, we move on to our website’s next page. Suppose you are registering someone new to your website, or you are saving new settings in a profile; just include this OTP creation, sending and validation somewhere in between your normal work flow.

In that way, your work flow will only proceed if the validation is true.

Here’s the code for checking the OTP. This is a simple step. Just check the user’s input string with the session stored value and validate the user.

$_SESSION['user'] = 1;                  // starts the session of the user and proceeds
header("Refresh: 0; URL=main.php");
$_SESSION['user'] = 0;                  // cancels session and logs out immediately
header("Refresh: 0; URL=index.php?m=0");  // an URL variable is passed on to show that OTP confirmation failed    

That’s it for PHP OTP creation and usage. Do let me know if you have better ideas and examples.

For all of you who are on BlogLovin, here’s my profile link do follow me – Follow my blog with Bloglovin

  • Wonderful tip. It is also protected one so no need to worry about security. Thanks a lot for sharing

  • Thanks to share take a look on it : Make OTP System in PHP

    • Thanks @ExamTayari for taking your time and reading my blog post. I am sure your article will be good enough too. Will surely read it.

      Have a great day!