Send SMS/OTP in PHP

Sending text messages from a website to an SMS supported device (like phone, tablet) is achieved via an SMS gateway. SMS gateways facilitate transmissions to and from a telecommunications network.

What we intend to cover here is basically an application to person (A2P) messaging system, commonly known as Bulk SMS.

php send sms

In India, Bulk SMSes are classified into two types:

Transactional SMS messages are largely informational like OTPs, order confirmations, bank transactions, delivery alerts, booking statuses, etc. They are sent to registered users and they do not have marketing content. On the contrary, those messages which are about discounts, offers, and other such advertisement related stuffs are known as Promotional SMS. They can only be delivered to non-DND numbers. In India, the TRAI has made a regulation that all non-transactional SMS messages (which includes promotional messages) can only be sent between 09:00 and 21:00 hours. You can read about the TRAI regulations here. Transactional SMS messages do not have time restrictions nor are they affected by the number's DND status.

In this tutorial, you will learn how to configure and send SMS via an SMS service provider in PHP. Instead of some random text, we will generate an OTP and send it as a text message to the desired recipent.

Generate OTP

To generate a four-digit OTP between 1000 and 9999, we use the PHP rand() function.

					
					<?php
						$otp = rand(1000,9999);	
					?>
					
				

Next we proceed to send it as a text message through an SMS Gateway. There are a plethora of SMS Gateway Service providers available out there, you can do some search and analysis for your needs and pick one. In this tutorial, I have picked 2Factor, which has one of the easiest API to set-up. We configure with it in the following section.

2FACTOR SMS Gateway

2factor sms gateway

Currently, 2Factor provides the following SMS packs for OTP.

2factor sms packs

Select one when you sign-up.

As shown above, we first generate a four-digit OTP between 1000 and 9999 with the rand() function and assign it to the variable $otp. And then there is the $phone variable which holds the phone number (including an ISD code) to be sent the OTP to.

Now the next important parameter to provide is the 36-character API Key. When you sign-up with 2Factor, an email would be sent to you providing the details of the cPanel, username and password. Login to your account, and in the splash page click on the Manage Account tab.

2factor manage account

There you will get your API Key.

Here is the configuration in PHP to send OTP via 2Factor Gateway Provider.

					
					<?php 
						$otp = rand(1000,9999);
						$phone = "+910123456789"; // target number; includes ISD
						$api_key = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'; // API Key						
						$req = "https://2factor.in/API/V1/".$api_key."/SMS/".$phone."/".$otp;				
						$sms = file_get_contents($req);
						$sms_status = json_decode($sms, true);
						if($sms_status['Status'] !== 'Success') {
							$err['error'] = 'Could not send OTP to '.$phone;
						}
					?>
					
				

On executing the script, an OTP will be generated and sent to the designated number. Here is what is looks like.

2factor otp

Should there be an error while sending SMS, it will be stored in the $err['error'] variable, which you can display it at the desired locaion.

TEXTLOCAL SMS Gateway

textlocal

There is also another SMS Gateway provider called Textlocal, which is quite popular. But it has a dependency class file called textlocal.class.php, which needs to be downloaded and included into the current script. You can download the file textlocal.class.php from here.

One important thing to note if you are considering Textlocal is that, by default, your SMS will be configured as promotional.

textlocal promotional configuration

NOTE: By default, Textlocal configures your account into Promotional SMS (check their FAQ section). So you will NOT be able to send SMS messages to DND numbers. So if you are experimenting, please choose a non-DND number to send to. To upgrade to Transactional SMS, you need to submit some business related documents.

If you are in India, there is a small modification you need to do in your textlocal.class.php. Inside the Textlocal class, change the first constant REQUEST_URL from https://api.textlocal.com/ to https://api.textlocal.in/.

textlocal class

Here also we generate a 4-digit OTP to send it to the intended number. Textlocal provides a 42-character API Key. You can get the key by logging in to your Textlocal account. Click on the Settings menu and select API Keys.

textlocal dashboard apikey
					
					<?php
						require('textlocal.class.php');
						$otp = rand(1000,9999);				
						$textlocal = new Textlocal(false, false, 
						'XXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
						$phone = '910123456789'; // ISD code prepended
						$numbers = array($phone);
						$sender = 'TXTLCL';
						$message = 'OTP: '.$otp;
						try {
							$result = $textlocal->sendSms($numbers, $message, $sender);
						} catch (Exception $e) {
							$err['error'] = $e->getMessage();
						}
					?>
					
				

If you intend to send SMS to more than one number, add them as elements to the $numbers array as follows. The numbers below have the ISD code (91) prepended to them and are from India.

					
					<?php			
						$numbers = array(910123456789, 910987654321);			
					?>
					
				

If any error is thrown during execution, it is set to $err['error'].

Notes

  • DND stands for 'Do Not Disturb'. As per the TRAI regulations in India, those who register their number in DND will not be receiving any promotional/bulk SMS.
  • Transactional SMS is delivered 24x7, irrespective of the recipent's DND status.