PHP Login with OTP Authentication

Login with an OTP code is a secure method for the user authentication process. In this method, a one-time password is generated dynamically and sent to the user who attempts login. OTP can be sent to the user’s email or his mobile phone. When the user enters the OTP code then the application will authenticate the user via this code.

In this tutorial, we are going to see an example to authenticate user login via an OTP code using email. In a previous tutorial, we have already seen a PHP code for login with username and password. In this example, when the registered user enters email to login, an OTP code is sent to the email address. Using this OTP code the user will be validated. Once the user uses this code then it will be invalid, meaning it cannot be used again. Also, this token will be valid for a day, then it will be expired.

Login form with OTP

The following code shows login form to the user to enter his email address. On entering email, it shows an input to enter the OTP code sent to his email address. After submitting OTP, PHP will validate the code and show authentication result to the user.

PHP Code to Validate OTP Authentication

On submitting the email address, PHP script validates the user by checking the user database whether it is registered email. If so, a 6 digit OTP code is generated dynamically by using the PHP rand() function. You may choose to substitute this random code generation logic using your preferred mechanism. This code is sent to the user’s email by using PHPmailer.

When the user submits the OTP code to PHP, it validates the code by checking its expiration. The code is valid for one day and it will be expired once it is used. The PHP code is,