How to Send Text Messages (SMS) with PHP

If you are trying to add an extra layer of security to your website, an additional channel of notifications, or build a service around text messages, then your search is over.

Twilio

The first thing you need to send text messages with PHP is to create an account with Twilio. Twilio is a service that allows developers to integrate voice calls and text messages into their projects. There are several services similar to Twilio but from my own experience I can attest that this is the one to work with.

Go ahead and visit the following link: https://www.twilio.com/try-twilio; you will be asked for your name, email, and a password. Make sure that you use a real email address as you will be required to verify your account. A phone number will be required as well in order to get the free trial.

Once you’ve verified your email address you should be able to log in and see your dashboard. At this point your account should have a trial balance of $15.00; this balance can only be used with verified numbers so be sure that you add at least one or two numbers.

In your dashboard there should be three key items:

  • Trial number
  • Account SID
  • Auth Token

Be careful with these three items as this is all you need to access Twilio’s set of REST APIs.

Sending a Message with PHP

Twilio provides us with more than just their set of APIs; they also provide developers with a helper library that will make this process much easier. For this part, we will make use of composer to install said library. In your terminal, change to the directory your project’s root is located in; once you are there go ahead and run the following command:

composer require twilio/sdk

Once the installation process is completed you may start using Twilio’s helper library in your project. Let’s start with a simple script to send a text message.

use Twilio\Rest\Client;

$client = new Client('YOUR_ACCOUNT_SID', 'YOUR_ACCOUNT_TOKEN');
$client->messages->create(
	$VERIFIED_NUMBER,
	array(
		'from' => $YOUR_TWILIO_NUMBER,
		'body' => 'Hello World!'
	)
);

That’s it! That’s all you need to send a message with Twilio. Now, this doesn’t mean that we are done. There are some improvements that can be made to the code above. In fact, if we were to make our own API endpoint we should add the following improvements:

  • Create API endpoint
  • Retrieve sensitive data such as credentials from the ENV file
  • Secure our endpoint
Route::post('/sms', function(Request $request){
	// Retrieve data from env file
    $account_sid = env('TWILIO_SID', false);
    $auth_token = env('TWILIO_TOKEN', false);
    $twilio_number = env('TWILIO_NUMBER', false);
    // Verify the given token matches the one in the server
    if(request('token') == $auth_token){
		// get destination number from the request
        $to_number = request('destination_number');
        $client = new Client($account_sid, $auth_token);
		// create message
        $client->messages->create(
            $to_number,
            array(
                'from' => $twilio_number,
                'body' => request('message')
            )
        );
		// Let your frontend know if it was successful
        // or if it to send the message
        return 'success';
    }else{
        return 'failure';
    }
}

That’s it (this time for real), you just created an endpoint within your Laravel application and should now be able to send messages making use of it. I recommend using Postman to test out your API endpoints. If you need a live server to test this out, I recommend you to try Digital Ocean.

If you have any questions or comments, let me know and I’ll do my best to help you out.

Leave a Reply

Your email address will not be published. Required fields are marked *