Advertisement
Scroll to top
Read Time: 5 min
Final product imageFinal product imageFinal product image
What You'll Be Creating

Introduction

In the prior episode, I wrote about preparing your application for SMS using Twilio, a commonly used texting service. In today's tutorial, I'll show you how to verify with SMS a user phone number for code messages, before transmitting a high volume of texts and running up your costs.

Before we get started, I want to encourage you to post questions and feedback in the comments. If you'd like to keep up on my future Envato Tuts+ tutorials and other series, please visit my instructor page.

Outlining the Process

After the user provides their phone number for code messages, we want to perform a handful of straightforward steps:

  • Generate a unique four-digit code.
  • Store their cell number and the four-digit code in our database (or encrypt the code locally as a hidden form variable on the page).
  • Send a text via SMS to the unverified phone number with the four-digit code.
  • Display a form asking the user to provide the code they received.
  • Verify the codes sent via SMS match.
  • Designate the number as verified in the database.

The User's Contact Page

In Meeting Planner, each user can add multiple contact methods, e.g. Skype, phone, etc. Each cell number must be verified via SMS to be used for SMS notifications.

The third row below shows a checkmark box which they can click to request verification:

How to Verify a Phone Number via SMS - Contacts listHow to Verify a Phone Number via SMS - Contacts listHow to Verify a Phone Number via SMS - Contacts list

Clicking that transfers the user to the actionVerify() controller below; note that it takes them to the else block at first because they've not yet submitted a code:

1
public function actionVerify($id)
2
{
3
    $model = $this->findModel($id);
4
    if ($model->load(Yii::$app->request->post())) {
5
    ...
6
    } else {
7
      $canRequest = $model->canRequest();
8
      if ($canRequest) {
9
        // send a text to this number

10
        $model->requestCode();
11
        return $this->render('verify', [
12
            'model' => $model,
13
        ]);
14
      } else {
15
        Yii::$app->getSession()->setFlash('error', $canRequest);
16
        return $this->redirect(['/user-contact']);
17
      }
18
    }
19
}

The method canRequest() checks if they've been requesting codes repeatedly or too frequently:

1
public function canRequest() {
2
    if ($this->request_count<UserContact::MAX_REQUEST_COUNT) {
3
      if (time() - $this->requested_at>=60) {
4
        return true;
5
      } else {
6
          return Yii::t('frontend','Sorry, you must wait a minute between requests.');
7
      }
8
    } else {
9
      return Yii::t('frontend','You have exceeded the maximum number of attempts.');
10
    }
11
  }

I make them wait a minute between attempts to reduce abuse.

Transmitting the Verification Code

If allowed, it calls requestCode():

1
public function requestCode() {
2
    $this->verify_code = rand(0,9999);
3
    $this->requested_at = time();
4
    $this->request_count+=1;
5
    $this->update();
6
    $sms = new Sms;
7
    $sms->transmit($this->info,Yii::t('frontend',
8
        'Please return to the site and type in {code}',['code'=>sprintf("%04d",$this->verify_code)]));
9
  }

This does the following:

  • Generates a random four-digit code.
  • It records the last moment in time (unix seconds) that a request to verify was made.
  • It increments the attempts of verification via SMS for this number.
  • And it stores all of this in the database.
  • Then, it transmits a text via SMS with the code that looks like the image below.
How to Verify a Phone Number via SMS - Text message with verification codeHow to Verify a Phone Number via SMS - Text message with verification codeHow to Verify a Phone Number via SMS - Text message with verification code

After requesting the code, saving it in the database behind the scenes and transmitting the code to the user, it loads the following form asking for the code:

How to Verify a Phone Number via SMS - Verify Contact Form requesting codeHow to Verify a Phone Number via SMS - Verify Contact Form requesting codeHow to Verify a Phone Number via SMS - Verify Contact Form requesting code

Verifying the Code

When the user attempts to submit a code, it runs the upper part of actionVerify():

1
public function actionVerify($id)
2
{
3
    $model = $this->findModel($id);
4
    if ($model->load(Yii::$app->request->post())) {
5
        // display verification form
6
        $model->verify = Yii::$app->request->post()['UserContact']['verify'];
7
        if (strval($model->verify_code) == strval($model->verify)) {
8
          $model->status = UserContact::STATUS_VERIFIED;
9
          $model->update();
10
          Yii::$app->getSession()->setFlash('success',Yii::t('frontend','Thank you, your number is confirmed.'));
11
          return $this->redirect(['/user-contact']);
12
        } else {
13
            Yii::$app->getSession()->setFlash('error', Yii::t('frontend','Sorry, that is incorrect. Please request a new code.'));
14
            return $this->redirect(['/user-contact']);
15
        }
16
    } else {
17
      ...
18
    }
19
}

It checks that the codes match. If they do, it updates the database to reflect the number has been verified. And it tells the user:

How to Verify a Phone Number via SMS - Successful confirmation noticeHow to Verify a Phone Number via SMS - Successful confirmation noticeHow to Verify a Phone Number via SMS - Successful confirmation notice

If not, it displays an error message:

How to Verify a Phone Number via SMS - Error try again after a minuteHow to Verify a Phone Number via SMS - Error try again after a minuteHow to Verify a Phone Number via SMS - Error try again after a minute

Try It Yourself

If you want to see this in action, you can sign up at Simple Planner or Meeting Planner (which is easy with a social account like Facebook or Google) and add a phone number. Then click the checkmark in the list that you'll see. That's it.

Wrapping Up

Obviously, if your application sends a lot of text messages via SMS, it's a notable cost of the business, and you want to limit abuse. That begins with setting up a firewall against invalid numbers—or valid numbers not actually owned by the impostor.

I hope you found this helpful. If you have any questions or suggestions, please post them in the comments. If you'd like to keep up on my future Envato Tuts+ tutorials and other series, please visit my instructor page. Definitely check out my startup series and Meeting Planner.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.