Send SMS Using PHP: 3 Best Options With Code Examples (2023)

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to Send SMS using PHP

SMS (Short Message Service) is a popular communication channel that allows businesses to interact with customers in real time. It is widely used for notifications, alerts, authentication, and marketing. Integrating SMS functionality into PHP applications can be valuable to any web-based business.

This article will explore different ways to send SMS using PHP. We will look at two options: sending SMS using SMTP in PHP and SMS using APIs in PHP. We will also explore three popular SMS APIs that can be used with PHP: Twilio, AWS SNS, and Clickatell. Finally, we will examine some alternative SMS APIs for sending SMS messages.

Comparison Chart | Send SMS using PHP

Here’s a quick comparison between Twilio, AWS SNS, and ClickaTell.

FeaturesTwilioAWS SNSClickaTell
Supported countries150+200+200+
API simplicityHighMediumHigh
Cost-effectivenessMediumHighMedium
Two-factor authenticationYesYesYes
Delivery statusYesYesYes
Multiple messaging channelsYesYesYes
AnalyticsYesYesYes
PersonalizationYesYesYes
ShortcodesYesYesYes
ScalabilityHighHighHigh
Customer support24/724/724/7

Article Highlights

  • Two options to send SMS are using SMTP servers or SMS APIs.
  • SMTP is a protocol for sending emails, but it can be configured for sms with minimal effort.
  • Local SMTP servers may require a lot of configuration and maintenance effort and technical expertise for server administration. 
  • Alternatively, an SMS API is a web-based interface that allows developers to send SMS messages using HTTP requests.
  • An SMS API service exposes a set of APIs for sending SMS seamlessly and removes the burden of setting up any local SMTP.
  • Before using an SMS API, some important factors are coverage, cost, throughput, and support.
  • Twilio, AWS SNS & ClickaTell are some popular SMS API services.

Table of Contents

#1 Send SMS using SMTP in PHP

Introduction

SMTP (Simple Mail Transfer Protocol) is a communication protocol that transfers emails between servers and clients. It works on the client-server model, where the client sends the email message, and the server receives and delivers it to the recipient’s email server. 

Send SMS Using PHP

Though it is a protocol for email, it is possible to send SMS messages using SMTP in PHP. This method is straightforward and does not require any additional setup or installation.

To send SMS using SMTP in PHP, you need to know the recipient’s phone number and their mobile carrier’s SMS gateway. The SMS gateway is the server that translates an email message into an SMS message and delivers it to the recipient’s phone number.

Challenges

Though sending SMS messages using SMTP in PHP is possible, it comes with some challenges.

  • Setting up a local SMTP server can be challenging, especially for those unfamiliar with server administration. 
  • It’s essential to ensure the server is secured and updated regularly to prevent potential security vulnerabilities.
  • Once the server is set up, it requires ongoing maintenance to ensure it operates correctly, such as monitoring email queues, blocklists, and bounce rates. 
  • Managing an SMTP server can be time-consuming and require a dedicated team to ensure reliable and uninterrupted operation. 

Therefore, many developers prefer SMS APIs that use HTTP to send text messages.

Pros & Cons

ProsCons
Cost-effectiveDifficult to set up locally
CustomizableComplex management
Widely availableLimited functionality
Full control over message deliveryReputation issues
Deliverability issues
Limited scalability

#2 Send SMS using SMS APIs in PHP

Introduction

SMS APIs provide a more reliable and robust way to send SMS messages from PHP applications. An SMS API is a web-based interface that allows developers to send SMS messages using HTTP requests.

It is relatively easy to get started with SMS API in PHP. Usually, we sign up for an account with the SMS provider and obtain an API key. The API key is a secret parameter not meant to be shared publicly. We then use the key as a token of authorization in code to send SMS.

Features

When choosing an SMS service for your application, some important features to consider are:

  • Country coverage: Ensure that the SMS service supports the countries where your users are located.
  • API simplicity: Look for an SMS service with a simple and intuitive API that is easy to integrate into your application.
  • Cost-effectiveness: Consider the cost of sending SMS messages and look for a service that offers reasonable rates or pricing plans that fit your budget.
  • Throughput: If you need to send a large volume of messages quickly, choose a service with high throughput.
  • CTR:  If your application requires users to take action, such as clicking on a link, choose a service that offers good CTR rates or supports features such as link shortening or tracking.
  • Two-factor authentication: If your application requires an added layer of security, look for an SMS service that supports two-factor authentication.
  • Delivery status: Choose a service that provides delivery status information so that you can track the success of your SMS messages.
  • Scalability: Consider the ability of the SMS service to handle a large volume of messages and scale as your user base grows.
  • Customer support: Look for a service that offers good customer support, with readily available resources or support staff to assist you in case of any issues or questions.

Limitations

Though it is a preferable way to send SMS using PHP, it does have limitations.

  1. Some providers charge per message, while others charge a monthly fee based on usage. The cost of sending SMS messages via an API can quickly add up. 
  1. SMS messages are limited to 160 characters, which can be challenging when conveying complex information. 
  1. Some SMS APIs may restrict certain types of content, such as promotional messages or messages containing sensitive information.
  1. Businesses rely on the provider’s infrastructure to deliver their messages using an SMS API. If the provider experiences downtime or technical issues, it can impact the delivery of SMS messages.
  1. Depending on the region in which the SMS messages are being sent, there may be various regulations that businesses need to comply with, such as obtaining explicit consent from recipients and including opt-out instructions in messages.

Pros & Cons

ProsCons
Global coverageAdditional setup required
Reliable deliveryAPI limitations
Supports message delivery trackingMay require additional fees
Supports large message volumes

Send SMS using PHP & Twilio

Introduction

Twilio is a popular cloud communication platform that provides APIs for sending SMS, voice, and video messages. It has a user-friendly web-based interface and a robust API that can be used to send SMS messages from PHP applications.

Send SMS Using PHP

Before using Twilio, you should sign up for an account and also purchase a Twilio phone number.

Installation

To use Twilio API in PHP, you need to install the Twilio PHP Helper Library. The library can be installed using Composer.

composer require twilio/sdk

Code Example

Here is an example code snippet that sends an SMS message using Twilio in PHP. Replace $sid and $token with your Account SID and Auth Token.

<?php


// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';


use Twilio\Rest\Client;


// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = "TWILIO_ACCOUNT_SID";
$token = "TWILIO_AUTH_TOKEN;
$twilio = new Client($sid, $token);


$message = $twilio->messages
                  ->create("++XXXXXXXXXXX", // to
                           [
                               "body" => "This is the ship that made the Kessel Run in fourteen parsecs?",
                               "from" => "+XXXXXXXXXXX"
                           ]
                  );


print($message->sid);


?>

Pros & Cons

ProsCons
Flexible pricing plansRequires extensive development knowledge for more advanced usage
Ability to integrate with Whatsapp and TelegramDocumentation can be improved.
Highly customizableRelatively costly for high traffic volumes
Versatile SMS API

Send SMS using PHP & AWS SNS

Introduction

Amazon Simple Notification Service (SNS) is a fully managed messaging service that enables you to send SMS, email, and mobile push notifications to subscribers or other applications. It has a flexible and scalable API that can be used to send SMS messages from PHP applications.

aws-sns

AWS SNS is a versatile service; we can write an entire article on its features, but here we focus on sending SMS using AWS SNS. With AWS SNS, you can send text messages to 200+ regions worldwide. 

Its highly customizable service allows you to optimize based on your use case. For instance – you can optimize between budget and reliability delivery, whichever is more important to your use case.

Installation

To use AWS SNS API in PHP, you need to install the AWS SDK for PHP. The SDK can be installed using Composer.

composer require aws/aws-sdk-php

Code Example

Here is an example code snippet that sends an SMS message using AWS SNS in PHP. Replace key and secret with your AWS access and secret keys.

<?php


require 'vendor/autoload.php';


use Aws\Sns\SnsClient;


$credentials = array(
    'key'    => 'your_access_key',
    'secret' => 'your_secret_key',
);


$client = new SnsClient([
    'version' => 'latest',
    'region' => 'us-east-1',
    'credentials' => $credentials
]);


$args = array(
    'Message' => 'Hello from AWS SNS!',
    'PhoneNumber' => '+15558675309'
);


$result = $client->publish($args);


print($result['MessageId']);


?>

Pros & Cons

ProsCons
Easy to integrate and implementLimited control as AWS SNS is fully managed service 
High availability and reliabilityCostly for large traffic volumes 
Good for large contact base

Send SMS using PHP & Clickatell

Introduction

Clickatell is a cloud-based messaging platform that provides APIs for sending SMS, email, and mobile push notifications. It has a scalable and reliable API that can be used to send SMS messages from PHP applications.

Send SMS Using PHP

ClickaTell is quite an early contender for the SMS API market, created 20 years ago. It has a vast reach to over 220 territories and 1000+ mobile networks.

Installation

To use Clickatell API in PHP, you need to install the Clickatell PHP SDK. The SDK can be installed using Composer.

composer require arcturial/clickatell

Code Example

Here is an example code snippet that sends an SMS message using Clickatell in PHP: Replace username, password and apiID with your unique values.

<?php


use Clickatell\Api\ClickatellHttp;
 
$clickatell = new ClickatellHttp("username", "password", "apiID");
$response = $clickatell->sendMessage(array(1111111111), "My Message");
 
foreach ($response as $message) {
    echo $message->id;
     
    // Message response fields:
    // $message->id
    // $message->destination
    // $message->error
    // $message->errorCode
 
}


?>

Pros & Cons

ProsCons
Ease on implementationLimited reporting and usage feedback
Integrates with Whatsapp seamlessly Whatsapp messaging is costly
Intuitive and well-structured documentation
Reliable and efficient service

Alternatives

Apart from the three API services we have seen already, here are some alternatives worth exploring.

Conclusion

In conclusion, there are several ways to send SMS using PHP, including SMTP and SMS APIs. While SMTP may be a viable option for those with the technical knowledge to set up and manage a server, SMS APIs offer most users a more straightforward and cost-effective solution. Among the SMS API providers, Twilio, AWS SNS, and ClickaTell are some of the popular choices, each with its own pros and cons.

 When selecting an SMS API service, it is important to consider factors such as country coverage, API simplicity, cost-effectiveness, two-factor authentication, delivery status, scalability, and customer support. Regardless of the chosen method, sending SMS using PHP can be a powerful tool for businesses and organizations to communicate with their customers in real-time.


Hope this article has been helpful. Stay tuned for more at FuelingPHP.

Dig Deeper with Our Email in PHP Examples and Guides

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.