Getting Started

Summary: An increasing number of web applications, android application and ios application have integrated SMS to notify users for Welcome message, OTP verification, Events, Sales or Coupons, directly through their mobile devices.

Let’s Begin

Before start we need some third party that provide sms service. So for this tutorial i am using MSG91 service to send sms.

MSG91 account

  1. Go to , Create new account or just click social login.

MSG91 Social login












2. Go to Dashboard and create your Sender ID like my sender id after creating Conyou.

MSG91 sender id







3. Go to Side menu and click on API Section and copy Authkey.










Note : MSG91 provide 250 Free Transactional SMS After that you need to purchase sms.

Let’s Begin

I assume that you already have sms service from msg91 using above setup or you can use any sms service providers like Twilio, Nexmo etc. Now i am creating a common function which you can call anywhere in your PHP code to send any type of text sms. 

For Best Practices you can create a constant file and put all your configuration keys in that file. For this i create a .env file where i put all my configurations .env this also used by some Popular PHP Framework Laravel and Symfony, So here my keys:

# MSG91 AUTH KEY and configuration parameters
# MSG91 ROUTE you can use this in your project without changing value

Just copy this function and paste in your helper class and call anywhere you want.

//send otp message
public static function sendMessage($mobile, $message)
    $message = urlencode($message);
    $url = sprintf("",
        env('MSG91_AUTH_KEY'), $mobile, $message, env('MSG91_SENDER_ID'), env('MSG91_ROUTE'));
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($ch);
    return $output;

How it's work here i am creating message creation function and finally call these two function to send otp.

//otp sms message helper
public static function sendOtpSms($name, $otp)
    $message = "Hi " . $name . "%0aThank you for showing interest in Lelocode. Your OTP is%0a" . $otp;
    return $message;
// Generate random four digit number
$four_digit_random_number = mt_rand(1000, 9999);
// call message helper function
$message = Helpers::sendOtpSms($full_name = 'Guest', $four_digit_random_number);
// get mobile number and add country code with mobile
$phone = '91' . $request->get('mobile');
// send message to mobile number
Helpers::sendMessage($phone, $message);

Congratulations, you have just integrated SMS API to your PHP application.Now it's your time to do some cool stuff using this code. Feel free to comment and ask any query if you stuck in your code or general questions.


Sign in to publish a comment


Be the first to comment on this post.