How to Send SMS in PHP Using Plivo’s SMS API

Your company has settled on Plivo to handle its voice and messaging communications, and now it’s your job to start integrating Plivo into your company’s applications. Don’t worry — Plivo has an SDK to help you out. Let’s see how to send and receive messages through Plivo in a PHP application.

Install the Plivo SDK

composer require plivo/plivo-php

or you can download the source from our GitHub repository, then run

composer install

Find your Auth ID and Auth Token

Choose a phone number

SMS regulations followed by carriers vary from country to country. For messages to countries other than the US and Canada, you might want to register an alphanumeric sender ID for your messages. You can learn more about the use of alphanumeric sender ID and register one from your Plivo Console.

Send an SMS message

<?php
require 'vendor/autoload.php';
use Plivo\RestClient;
$client = new RestClient("<auth_id>","<auth_token>");
$message_created = $client->messages->create(
'+14151234567',
['+14157654321'],
'Hello, world!'
);

Replace the placeholders auth_id and auth_token with actual values from your Plivo Console. Save the file and run it.

Note: If you’re using a Plivo trial account, you can send messages only to phone numbers that have been verified with Plivo. You can verify a phone number using the Sandbox Numbers page of the Console.

Receive an SMS message

Use this code to start a local server:

<?php
require 'vendor/autoload.php';
$from_number = $_REQUEST["From"];
$to_number = $_REQUEST["To"];
$text = $_REQUEST["Text"];
echo("Message received - From $from_number, To: $to_number, Text: $text");

Save this code in any file — we’ll call ours receive_sms.php. To run this file on the server, go to the folder where this file resides and issue the command

php -S localhost:8000

That’s fine for testing, but it’s not much good if you can’t connect to the internet to receive incoming messages and handle callbacks. For that, we recommend using ngrok, which exposes local servers behind NATs and firewalls to the public internet over secure tunnels. Install it and run ngrok on the command line, specifying the port that hosts the application on which you want to receive messages:

./ngrok http [portnum]

Ngrok will display a forwarding link that you can use as a webhook to access your local server using the public network.

Now you can create an application to receive SMS messages (follow our Quickstart guide for details).

Conclusion

Haven’t tried Plivo yet? Getting started is easy and only takes 5 minutes! Sign up today.

Originally published at https://www.plivo.com on Feb 24, 2021.

Developer Evangelist