Implement One Time Password Login & Signup with Yii 2 PHP and Twilio SMS
Time to read: 5 minutes
In recent years, the user signup and login process have not only been built around an email and password, but increasingly the user’s phone number and a One Time Password (OTP) for improving security. In this tutorial we’ll build a basic Yii 2 App with signup/login functionality and for authentication, an OTP sent via Twilio Programmable SMS will be used.
Note: The application code and files used in this tutorial are available in this repo.
Prerequisite
For this tutorial we’ll assume you:
- Have a PHP development environment e.g XAMPP, WAMP
- Are familiar with PHP and MySQL (PhpMyAdmin)
- Are familiar with Yii 2 Framework
- Have a Terminal (Command Line)
- Have Composer installed
- Have a Twilio account with SID, Auth Token and Twilio Phone number available
- Have basic knowledge of Javascript & Jquery
Create a new Yii 2 App
We’ll start off by installing a new Yii2 Project. After a successful installation you should see the default Yii2 homepage.
Setup Database Connection
Next step is to create a database for our installed app to use. Create a database named twilio_sms
from your PhpMyAdmin or MySQL terminal. Once done, open the config
folder in your newly installed Yii 2 project and set the right database configuration details in the db.php
file.
Create a User Table
A User table will store the users details. For this tutorial we’ll keep the columns/fields to a minimum to focus on OTP Authentication. Use the following MySQL Command to create a table named tbl_user
.
The otp
field in the table stores the random OTP generated for a phone number, and otp_expire
contains the time (Unix timestamp format) up to which an otp is valid for.
Setting up Models
User Model
Yii 2 basic setup comes with static users defined in an array inside User Model /models/User.php
. However, we’ll make this model dynamic by connecting it to the table we created above. We’ll follow this Yii 2 Authentication guide page to setup our model. After implementing, User.php
will look like this:
You’ll notice that a findyByPhone()
function is added in the model to find a user by the phone number.
Login Model
After modifying the User Model, our next step is to modify the existing LoginForm located at /models/LoginForm.php
. We will be changing the getUser()
function as we’ll be finding a user by their phone number. The login()
function will have the code to empty the OTP before the user logs in so that the same OTP doesn’t work for multiple logins. Also we have added an attributeLabels()
function to assign labels to the username
and password
property of the form.
Add the Twilio SDK
Before we modify any other files, lets first add the official Twilio PHP SDK in our project. To install run the following command inside the root directory of your project:
After installation, we’ll configure Twilio's SID, Auth Token and Phone number in the /config/params.php
file like below:
Make an OTP request+submit Form
On our Login/Signup form we’ll have two sections, one for requesting a OTP, and another for submitting the OTP. The fields & buttons in the section are as follows:
- Section 1
- Phone Number field - User will enter their phone number in E.164 Format
- Send OTP button – After filling in the phone number, the user will click on this button to request a OTP. The request will be Ajax based so that the page doesn’t reload. If the OTP is sent successfully to the user’s phone Section 1 will hide and Section 2 will be displayed to Enter the OTP.
- Section 2
- OTP field – Here the user will enter the received OTP
- Login button – Clicking on this button will submit the phone number and the OTP via Ajax. If the credentials are correct, a “Login success” page will be displayed. Otherwise, an alert will show up saying “incorrect OTP”.
The Yii2 basic app does come with a login form /views/site/login.php
and we’ll use the same form and modify it according to the fields and functionality discussed above. The Form code will be like this:
As you can see after the form end tag, there is a sendOTP()
Javascript function which is called on click of the “Send OTP” button. It first validates the Phone Number field and if the field passes the validation, sends a POST Ajax request containing the phone number to (the not yet created) send-otp action of site controller. If the request’s response returns True
then “Section 2” is displayed to enter the OTP received, otherwise error message is displayed in alert box.
The Login()
function is called on the click of the “Login” button, which is similar to sendOTP()
. First it validates the Password field and then posts the whole form including Phone number to the login action of the site controller in an Ajax request. On successful authentication, the page is redirected to the home page. In case of wrong credentials or error, an alert is displayed containing the error message.
Make an OTP request and Login Action
It’s time to make/modify the aforementioned actions of sending an OTP and login in /controllers/SiteController.php
to complete the task.
The send-otp action will:
- Receive the phone number posted by a user in the Login form.
- Find the user by phone number and incase user doesn’t exist, it’ll create one with that number.
- Set a random 6-digit OTP and send it using Twilio SMS.
- Return a success or failure (with error message) response in JSON format.
The action will be like this:
Once the send-otp action is added, you can enter the phone number in the login form and request an OTP. Our next step is to modify the existing login action in site controller. This action will:
- Load and render the login form in a GET request (when user enters the URL in browser or clicks on the login link).
- Redirect user to homepage if already logged in.
- Attempt login with the credentials (Phone number & OTP) sent via Ajax POST request.
- Login user and send a success response in JSON format if credentials are valid.
- Send a failure response with error message in JSON format in case of failure/wrong credentials entered.
Considering the above points, The Login action will be like the below code:
Lets update the verbs & access control in the behaviors()
function of site controller and add the send-otp & login actions.
Testing the App
After all the coding in different files and running different commands, our OTP based signup and login system is now ready to be tested. Go to the Home Page of your Yii2 App and click on the Login link in the top right corner. You will see a page like below:
Enter any valid phone number and click on Send OTP button to receive the code.
Note: If you are on a Twilio trial account the numbers you can send an SMS to are limited to verified numbers only. For more info check this page.
Once the code is successfully sent, you’ll get an alert with message “OTP Sent and valid for 10 minutes.” Clicking on OK, you’ll see a text field to enter the OTP with the Login button like below:
On entering the valid OTP and then clicking on the login button you’ll be greeted with an alert saying “Login Successful”. After clicking “OK” on the alert, you’ll be redirected to the site/index
page which will have the Logout button and the logged in user’s Phone number instead of the Login button.
Conclusion
Now that you have completed this tutorial, you know how to:
- Include the Twilio PHP SDK in Yii2 Application
- Send an SMS via Twilio
- Verify a Phone number
- Login a user using phone number and OTP
Next, you can try to validate a phone number using Twilio Lookup API before sending an OTP. And to make our app cooler you can try getting the OTP via phone call by implementing the Twilio’s Voice API.
Any questions about this tutorial? Hit me up on Twitter @razorsharpshady.
Twitter: twitter.com/razorsharpshady
Email: a.kandari391@gmail.com
GitHub: github.com/razorsharpshady
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.