Home
Separator
Blog
Separator

How to Send an SMS Using PHP

Diana Nersisyan
Diana NersisyanProduct Owner

Published: Jul 4, 2023

PHP SMS

Short for PHP: Hypertext Preprocessor, PHP is a scripting language designed for the creation of dynamic applications as well as web pages. It is open-source, easy to use, and enjoys massive community support, making it a go-to choice for server-side development. PHP has also proven to be useful in SMS integrations

By using PHP to integrate SMS functionality into web applications, businesses can send timely alerts, reminders, and notifications to their customers directly on their mobile phones. In this article, you’ll learn all about using PHP for SMS messaging purposes, including how to send an SMS with a PHP script in three different ways. 

Advantages of Using PHP for SMS

Easy to Learn

PHP is known to be one of the most straightforward scripting languages. It has a logical and well-organized syntax as well as command functions that are easy to understand. In comparison with other languages, you don’t need a manual or to go through intensive study. This makes it easy for developers to work with.  

Highly Flexible

Flexibility is essential when it comes to scripting, and PHP delivers on that end. What’s best about this scripting language is that it allows you to make modifications even after the project has started. This helps save a great deal of time. Writing codes or command functions wouldn’t be necessary; a PHP developer can simply make changes to the existing code.

advantages-of-using-php-for-sms

Compatible With Most Operating Systems

Another upside of using PHP to send an SMS to mobile phones is that it’s compatible with most operating systems. You can run the code on various platforms, including Linux, UNIX, and Solaris. And since it enables seamless integration with other technologies like Java, you don’t need to redevelop existing software, which is great for saving both time and money. 

Cost-Efficient

Being an open-source scripting language, PHP is completely free to use. There are no expensive licenses or software that you’ll need to buy. This enables developers to send SMS via PHP as cost-efficiently as possible without having to deal with any additional expenses. 

More Control for Developers

As opposed to other scripting languages, PHP gives more control to developers. You can make the code more dynamic by adding or mixing tags. Moreover, you don’t need to worry about entering codes and functions in a certain order, as long as they fall between tags. 

what-you-should-know-before-using-php-to-send-messages

What You Should Know Before Using PHP to Send Messages

On its own, PHP doesn’t have a messaging module or functions, and it doesn’t enable you to send SMS messages. Sending messages with this scripting language requires a GSM provider that offers a PHP API to implement the functionality. To get started with SMS messaging via a PHP API, you’ll need to get access to the API documentation. Make sure to check whether the API methods meet your business messaging needs. 

The first step involves authentication. Keep in mind that methods of authorization—such as Bearer, Digest, OAuth, and Basic Auth—differ from one provider to another. You’ll also want to have PHP installed on your server and a text editor to write PHP codes. Certain providers offer the option to download PHP libraries for a smoother process. Finally, be sure to test the service by writing a PHP code based on the documentation. 

Text Message API Service Pricing

Dexatel employs a pay-as-you-go approach that charges you per sent message. This is the most affordable SMS gateway pricing model, and the service costs are free of setup, monthly, or any other fees.

When you’re coding for SMS, there are certain parameters that define the various aspects of the message you want to send. These consist of the sender, the receiver, the text, as well as the communication channel. 

  • The “from” parameter is the sender ID from which you’re sending your SMS message. An alphanumeric sender ID can contain a maximum of 11 characters, whereas phone numbers can have up to 15 characters

  • The “to” parameter refers to the phone number of the recipient. You‘ll want the phone numbers to be in international format with the destination country code

  • The “message” parameter is where you’ll want to enter the message content. It can contain up to 1,000 characters. If the text happens to be longer than 160 characters (70 for unicode), it will be divided into more than one text message

As far as the “channel” parameter goes, it is optional and lets you use PHP to send texts from your preferred channel. You may switch between channels just by modifying the value of this parameter. 

sending-an-sms-text-in-php-using-dexatels-sms-api

Sending an SMS Text in PHP Using Dexatel’s SMS API

This method involves sending messages via an SMS service with PHP. Using an SMS API essentially enables you to integrate messaging into your application. You can also use it for two-way communication with customers. It’s an excellent solution for keeping your services live at all times and providing your audience with timely notifications. 

What’s great about SMS APIs is that they require minimal coding. API features also include analytics and click-through rates. It’s also a faster method than SMTP to SMS. One downside is that if you need to connect with customers via different channels, you’ll have to add each of those channels separately. 

The process involves implementing PHP code with an SMS API service like Dexatel. For this method, we’ll be using Dexatel’s API as an example. Here’s what you’ll need to do to send an SMS using PHP:

  1. Sign up for an account and set up a sender ID

  2. Create an API key and send an HTTP POST request to Dexatel Endpoints. Here’s an example of an SMS request with PHP:

<?php

require_once 'HTTP/Request2.php';

$request = new HTTP_Request2();

$request->setUrl('https://api.dexatel.com/v1/messages');

$request->setMethod(HTTP_Request2::METHOD_POST);

$request->setConfig(array(

'follow_redirects' => TRUE

 ));

$request->setHeader(array(

'Content-Type' => 'application/json',

'X-Dexatel-Key' => '0940dXXXXXXXXXXXXXXXXXX'

  ));

$request->setBody('{\n"data": {\n"from": "Dexatel2",\n"to": [\n"18558675310"\n],\n"text": "This is my test message",\n"channel": "sms"\n}\n}');

try {

$response = $request->send();

if ($response->getStatus() == 200) {

echo $response->getBody();

 }

else {

echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .

$response->getReasonPhrase();

  }

  }

catch(HTTP_Request2_Exception $e) {

echo 'Error: ' . $e->getMessage();

 }

This is an example of a Json response:

{

 "data": [

 {

 "id": "e4a2bcXXXXXXXXXXXXXXXXXXXXXX",

"account_id": "78427XXXXXXXXXXXXXXXXXXXXXXX",

"text": "This is my test message",

"from": "Dexatel2",

"to": "18558675310",

"channel": "SMS",

"status": "enroute",

"create_date": "2023-06-12 12:00:42",

"update_date": "2023-06-12 12:00:42",

"encoding": "GSM-7",

"segment_count": 1

 }

 ]

 }

sending-an-sms-text-in-php-using-a-multichannel-notification-api

Sending an SMS Text in PHP Using a Multichannel Notification API

Multichannel notification APIs refer to those which developers use for sending notifications through multiple communication channels via a single interface. These APIs maintain a clean codebase by eliminating the complexities of integrations with various channels. This allows developers to write clean and modular codes that interact with a uniform API. Multichannel notification APIs also allow for scalability by making it easier to add or remove channels without any major code changes. One common reservation around this option is that there’s a price associated with the benefits. 

Start by choosing a multichannel notification service such as Courier (which we’ll be using in this scenario). You’ll first need to create an account and carry out the initial setup. This generally involves entering your name, selecting SMS, choosing PHP as the backend programming language, and choosing your SMS provider. You’ll also need to provide the number associated with your provider as well as the API key. With the initial setup out of the way, you can move on to the next step. 

  1. Select “Create Notification” and preview how it will appear on the recipient’s phone

  2. Install the Courier SDK (composer require trycourier/courier)

  3. Copy and paste the PHP snippet generated by Courier. Here’s how it will look like:

<?phprequire "./vendor/autoload.php";

use Courier\CourierClient;

$courier = new CourierClient("https://api.courier.com/", "YOUR_AUTH_TOKEN_HERE");

$result = $courier->sendEnhancedNotification(

 (object) [

  'to' => [

'phone_number' => "RECIPIENT NUMBER HERE",

 ],

'template' => "F3Q0EWXH5W4S70H4CS99695STCYX",

'data' => [

'recipientName' => "Indrajith",

    ],

  ],

 );

echo( $result->requestId );

?>

You can check the status of your SMS text by going to the Logs in the Courier dashboard. There, you’ll be able to view different statuses of messages, including queued, sent, and opened. Courier will also inform you of any errors in the delivery process. 

sending-an-sms-text-in-php-using-smtp

Sending an SMS Text in PHP Using SMTP

Short for Simple Mail Transfer Protocol, SMTP is the most common method of sending system-generated emails. But besides sending and receiving emails, you can also use SMTP with PHP to send text messages. This involves making use of a third-party application as an intermediary between the mobile phone and the mail server. 

The primary benefit of sending SMS messages with SMTP is that you’d essentially be using your email client. You can implement this method with minimal coding, and it won’t take any longer than 10 minutes. But since the messages go back and forth through the SMS gateway, there's always a risk of failed delivery. 

To send a text message using SMTP, you’ll need the recipient’s phone number and the name of the carrier. Once you have those, simply follow these steps:

  1. Start by entering PHP’s mail function signature 

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string     $additional_parameters ]] )

Run the edit function signature before adding it to the PHP code

<?php

var_dump( mail( '[email protected]', '', 'This is a Test Message.' ) ); 

?>

Wrapping Up

Being a flexible scripting language, PHP has seen great use in SMS integrations. And when it comes to using PHP to send text messages, the three aforementioned methods come to mind—namely SMS API, the multichannel notification API, and SMTP. Accounting for the benefits and drawbacks of these methods enables you to make an informed decision. Ultimately, you should choose the one that best suits your business needs and preferences.