Generate OTP in Codeigniter & Send Via SMS

OTP (One Time Password) is used by every major or minor company around the world to verify their users. In the modern world, either web or mobile applications leverages the power of OTP to quickly log in their user, verify the genuineness of users or just to verify the phone number of users so that any spam or abuse of the system can be prevented.

You can download the complete project files at the bottom of the article.

What We Are Going To Learn?

In this tutorial, you are going to learn how we can generate an OTP in Codeigniter and send it via SMS using the Twilio API. You will learn how to configure and send SMS using Twilio.

Prerequisite.

You must have basic knowledge of Codeigniter framework to follow along. You should know how to use composer to download & install the PHP packages because we are going to use third-party packages for this demo. For the frontend of this demo, I am going to use Bootstrap CSS, So in order to understand the design, you must be familiar with the Bootstrap CSS.

Installations.

For this tutorial, we need to install two things
1. Codeigniter framework itself. To install the CodeIgniter open up a terminal inside the htdocs folder of your XAMPP install & fire this command

composer create-project codeigniter/framework otpdemo

Here otpdemo is our project directory name, you give any suitable name you want.

2. Since we are going to use Twilio to send our OTP via SMS, So we need to install a package which is provided the Twilio itself to send SMS via their API, inside the project directory fire this command in the terminal,

composer require twilio/sdk

Step 1: Setting Up The Twilio Account.

Go to the twilio.com & quickly sign up so that you can access the dashboard where we will do all the things.

Now go to this URL “//www.twilio.com/console/sms/dashboard”  to get your API credentials. We will need these credentials to send the SMS via our code.

Twilio get API credentials

Twilio get API credentials

Now after getting the API credentials, we need a phone number to send SMS with. Twilio provides one testing phone number with which you can send the SMS for testing purpose.

Let’s set up our testing phone number. Open this URL “//www.twilio.com/console/sms/getting-started/build”. You will a small text like “get a phone number”  click on this link & set up your phone number. After successfully setting up your phone number you will see something like this,

Twilio setup phone number

Twilio setup phone number

Now we can use this information to send our OTP via SMS using our code.

Step 2: Creating Views.

We will need two pages for this tutorial, One page will have a form where you can enter your phone number and send an OTP. The second page will be for verification purpose where you can enter the received OTP and verify it. Create these two files in the application/views folder.

otpdemo.php

<!doctype html>
<html lang="en">

<head>
    
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link href="//getbootstrap.com/docs/4.3/examples/floating-labels/floating-labels.css" rel="stylesheet">
    <title>OTP Demo In Codeigniter</title>
</head>

<body>

    <body>
        <form class="form-signin" action="<?= base_url('OTPmanager/send_otp_sms') ?>" method="POST">
            <div class="text-center mb-4">
                <img class="mb-4" src="//newcodingera.com/wp-content/uploads/2018/12/Untitled-1.png?x26402" alt="" width="100%" height="72">
                <h1 class="h3 mb-3 font-weight-normal">Codeigniter OTP Demo</h1>
            </div>

            <div class="form-label-group">
                <input type="text" id="phone-number" name="phone" class="form-control" placeholder="Enter Phone Number" required>
                <label for="phone-number">Enter Phone Number. Ex +911010101010</label>
            </div>

            
            <button class="btn btn-lg btn-primary btn-block" type="submit">Send OTP</button>
            <p class="mt-5 mb-3 text-muted text-center">&copy; 2017-2019</p>
        </form>
    </body>

    <!-- Optional JavaScript -->
    <script src="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>

</html>

otpverify.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link href="//getbootstrap.com/docs/4.3/examples/floating-labels/floating-labels.css" rel="stylesheet">
    <title>OTP Demo In Codeigniter</title>
</head>
<body>
    <body>
        <form class="form-signin" action="<?= base_url('OTPmanager/verify_otp') ?>" method="POST">
            <div class="text-center mb-4">
                <img class="mb-4" src="//newcodingera.com/wp-content/uploads/2018/12/Untitled-1.png?x26402" alt="" width="100%" height="72">
                <h1 class="h3 mb-3 font-weight-normal">Enter your OTP To verify</h1>
            </div>

            <div class="form-label-group">
                <input type="text" id="otp" name="otp" class="form-control" placeholder="OTP" required>
                <label for="phone-number">Enter OTP</label>
            </div>

            <button class="btn btn-lg btn-primary btn-block" type="submit">Verify OTP</button>
            <a href="<?= base_url('OTPmanager') ?>" class="btn btn-lg btn-danger btn-block" type="submit">Back</a>
        </form>
    </body>
</body>
</html>

Our UI will look like this,

otpdemo.php

otpdemo.php

otpverify.php

otpverify.php

Step 3: Creating a Controller.

Let’s create a controller which will handle all the incoming request. Create an OTPmanager.php named controller in the application/controllers folder.

OTPmanager.php

<?php

defined('BASEPATH') or exit('No direct script access allowed');

// Load the autuloader
require_once FCPATH . '/vendor/autoload.php';

use Twilio\Rest\Client;

class OTPmanager extends CI_Controller
{
    private $sid;
    private $token;

    public function __construct()
    {
        parent::__construct();
        $this->sid = "YOUR_SID_HERE";
        $this->token = "YOUR_TOKEN_HERE";
    }

    public function index()
    {
        $this->load->view('otpdemo');
    }

    public function send_otp_sms()
    {
        $otp = $this->generate_otp();

        // For demo I'm using session to store the OTP,  you might want to store it in the DB
        $_SESSION['user_otp'] = $otp;

        // Reciever's phone number
        $phone_number = $this->input->post('phone');

        // Create Twilio client
        $client = new Client($this->sid, $this->token);

        // Use the client to do fun stuff like send text messages!
        $client->messages->create(
            // the number you'd like to send the message to
            $phone_number,
            array(
                // A Twilio phone number for testing purpose
                'from' => '+17207105103',
                // the body of the text message you'd like to send
                'body' => 'Here is your OTP! ' . $otp
            )
        );

        // Redirect to the verfication page
        redirect(base_url('OTPmanager/verfiy'));
    }


    public function verfiy()
    {
        // Load the form to verfiy OTP
        $this->load->view('otpverify');
    }


    public function verify_otp()
    {
        // Get the otp value 
        $user_otp = $this->input->post('otp');

        if ($user_otp == $_SESSION['user_otp']) {
            echo " OTP is valid...";
        } else {
            echo "This OTP is invalid Or expired!!!";
        }
    }


    private function generate_otp(int $length = 4)
    {
        $otp = "";
        $numbers = "0123456789";

        for ($i = 0; $i < $length; $i++) {
            $otp .= $numbers[rand(0, strlen($numbers) - 1)];
        }

        return $otp;
    }
}

/* End of file OTPmanager.php */

Here I have written a small method to generate a random number which can be used as OTP. For simplicity, I have only considered the numeric OTP with a length of four digits but you can include the alphanumeric values in the OTP.

For the verification part, I am using the session to store the generated OTP but I highly recommend you to store them in the database. You can create a column in the user’s table to store the generated OTP.

Step 4: Sending The OTP Via SMS

Now got to the //localhost/otpdemo/index.php/OTPmanager/ in the browser and enter your phone number with the country to receive an OTP.

Enter your phone number

Enter your phone number

I have received the OTP like this,

OTP SMS

OTP SMS

 

Conclusion.

You have learned how you can generate & send OTP using Codeigniter. Now you can easily use this code to send the OTP via email if you want. The only difficult & time-consuming part is setting up the Twilio account.

If you have any suggestions or if you face any problem please write it down in the comment box…

Happy Coding…:)

Download The Complete Project

Create URL Shortener in NodeJS

 

Ropali Munshi
Ropali Munshi
Ropali Munshi is fullstack PHP Developer. He is passionate developer who loves to learn and expirement with new programming languages , libraries and frameworks. Nowdays he is more into the JavaScript realm.

6 Comments

  1. Monsur Ahmed says:

    not working. given error your code

  2. Monsur Ahmed says:

    Deprecation warning: require-dev.mikey179/vfsStream is invalid, it should not contain uppercase characters. Please use mikey179/vfsstream instead. Make sure you fix this as Composer 2.0 will error.

  3. Monsur Ahmed says:

    finnaly work

  4. i m facing this problem
    An uncaught Exception was encountered
    Type: Twilio\Exceptions\RestException

    Message: [HTTP 400] Unable to create record: The ‘To’ number +93439866887 is not a valid phone number.

    Filename: C:\xampp\htdocs\ci\vendor\twilio\sdk\Twilio\Version.php

    Line Number: 85

    Backtrace:

    File: C:\xampp\htdocs\ci\vendor\twilio\sdk\Twilio\Version.php
    Line: 219
    Function: exception

    File: C:\xampp\htdocs\ci\vendor\twilio\sdk\Twilio\Rest\Api\V2010\Account\MessageList.php
    Line: 64
    Function: create

    File: C:\xampp\htdocs\ci\application\controllers\AOR\otp.php
    Line: 50
    Function: create

    File: C:\xampp\htdocs\ci\index.php
    Line: 315
    Function: require_once

    • Ropali Munshi says:

      As per my guess, this error is related to your account settings. You might want to check the phone number you have been assigned to use.

Leave a Reply

Your email address will not be published. Required fields are marked *

You Don't Want To Miss It!

Please subscribe to our newsletter. Every week I share tips, tricks, tutorials, free books & video course directly in your inbox.