Send an SMS Message with PHP
Note:
Before you can get started, you need the following already set up:
- Set all SMS API configuration settings.
- PHP 7.3.0 or later and a familiarity with how to create a new file.
- cURL 7.61.0 or later installed
This script will enable you to send an SMS message using PHP and the Sinch SMS API.
Steps:
- Set up your PHP file.
- Send your first SMS message.
Set up your PHP file
Create a file (example: send_sms.php
) and add the supplied sample code.
Send SMS
<?php
$service_plan_id = "YOUR_servicePlanId";
$bearer_token = "YOUR_API_token";
//Any phone number assigned to your API
$send_from = "YOUR_Sinch_virtual_number";
//May be several, separate with a comma ,
$recipient_phone_numbers = "recipient_phone_numbers";
$message = "Test message to {$recipient_phone_numbers} from {$send_from}";
// Check recipient_phone_numbers for multiple numbers and make it an array.
if(stristr($recipient_phone_numbers, ',')){
$recipient_phone_numbers = explode(',', $recipient_phone_numbers);
}else{
$recipient_phone_numbers = [$recipient_phone_numbers];
}
// Set necessary fields to be JSON encoded
$content = [
'to' => array_values($recipient_phone_numbers),
'from' => $send_from,
'body' => $message
];
$data = json_encode($content);
$ch = curl_init("https://us.sms.api.sinch.com/xms/v1/{$service_plan_id}/batches");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BEARER);
curl_setopt($ch, CURLOPT_XOAUTH2_BEARER, $bearer_token);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if(curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
} else {
echo $result;
}
curl_close($ch);
?>
Fill in your parameters
- Assign your values found in the your Sinch Customer Dashboard to the following parameters:
$service_plan_id = "YOUR_servicePlanId"; $bearer_token = "YOUR_API_token"; //Any phone number assigned to your API $send_from = "YOUR_Sinch_virtual_number"; //May be several, separate with a comma , $recipient_phone_numbers = "recipient_phone_numbers"; $message = "Test message to {$recipient_phone_numbers} from {$send_from}";
- Now, in the string portions in the code below, write your message:
$message = "Test message to {$recipient_phone_numbers} from {$send_from}";
- That's it! Just copy the rest of the script into your file, save, and you'll be sending messages in no time.
Send your first SMS message
Execute the code and send your test SMS message with the command below:
php send_sms.php
Additional resources
Visit our API specification to test more endpoints.