In today’s world, instant communication is crucial for businesses and developers alike. One of the most effective ways to achieve this is through SMS. Whether it’s for notifications, reminders, or alerts, sending SMS messages can significantly enhance user engagement. This article will guide you through the process of sending SMS messages using PHP, a popular server-side scripting language. We’ll start with a raw PHP script and then use a minimal web application framework.
Prerequisites
- PHP 8.1+
- Composer for package management
- A Vonage API Account
To complete this tutorial, you’ll need a Vonage API account. If you don’t have one, you can sign up today and start building with free credit.
Once you have an account, you can find your API Key and API Secret at the top of the Vonage API Dashboard.
How to Send Text with Raw PHP
First, create a new Composer project and pull in the Vonage PHP SDK. Using the command line, run the following commands:
Open the new PHP file and make sure Composer’s autoload is included:
To send an SMS, you’ll need:
- A set of credentials from the Vonage Dashboard
- A Client object
- A text message to send
Here’s the final code:
Replace the placeholder constants with your actual details and send the message.
How to Send SMS Using Slim Framework
For the second example, we’ll use the Slim Framework. Install it with Composer:
The second command installs Slim’s PSR-7 (Request Interface) implementation. We’ll create a route that takes a POST request with a JSON body containing the text message.
Here is the modified send-sms.php
file:
Now we have a route where you can send the message text to a server for it to complete the process. You can, of course, add additional keys to the JSON payload to add the from and to cellular numbers. Experiment with different SMS gateway providers and explore additional features like receiving SMS messages and managing contacts to further enrich your application.