Centro de Conocimiento
Explore nuestra biblioteca de información sobre nuestros productos y servicios
How to send SMS with PHP and SMS API
It is easy and simple to add SMS sending to any PHP-based website or application. You only need to know the basics of PHP and have a platform for sending SMS messages that lets you use an SMS API like the one provided by SMS Connexion.
How to integrate SMS API to send SMS using PHP?
PHP is the most popular programming language for making websites or software that can be used online. PHP is a programming language and technology that is used by platforms like WordPress, Laravel, Joomla, PrestaShop, Drupal, and many others.
SMS API enables the integration of SMS messaging into your application. You can use this to send SMS messages automatically and quickly let customers know about things and send them notifications.
Before you begin
To get started, you will have to do the following:
- Create an account at SMS Connexion and login.
-
To make API requests you need your credentials. Our API supports authentication with two options: API Key or Access Token (Oauth 2.0).
-
For API Key: Go to the HTTP API > API Keys, and create one by clicking on the "New API Key" button.
-
For Access Token (Oauth 2.0): Go to the HTTP API > API Tokens (Oauth 2.0) and click on "New application".
-
- Copy the credentials generated in the previous step for further use in the PHP code.
How to send SMS using PHP in few easy steps
Set up your PHP file
Create a file (for example, send-sms.php) and insert the PHP sample code in it.
Sample PHP code for SMS API integration
To send SMS with PHP you need to make an HTTP POST request to the API endpoint, with your authorization credentials in the Header and the text message details (to, from, text) in the Body in JSON format.
The minimum parameters that your API request should have are:
-
to: this is the phone number where the SMS will be sent. It should be in international format E.164.
e.g. +4915123xxxxxx for Germany, +3361231xxxx for France, +39312311xxxx for Italy
This parameters accepts one phone number or multiple phone numbers (up to 25.000 in one request)
Example of valid JSON formats for the "to" parameter:
"to": "+49151235698x"
"to": ["+49151235698x"]
"to": ["+49151235698x", "+3361231073x", "+39312311443x", "+447400445103"]
-
from: this is the sender ID (also called sender name or originator) of the text message. For alphanumeric sender names, it can have between 3 and 11 characters, and for numeric sender IDs, it can have up to 15 characters (a-zA-Z0-9). No special characters are allowed (e.g. ! @ # " ? ^ etc.).
-
text: the text of your SMS message. It can have up to 160 characters if you use characters from GSM alphabet or 70 characters if you use Unicode characters. If you go over this character limit, the SMS will be split into multiple parts of 153 (for GSM) and 67 characters (for Unicode), and will be concatenated into one long SMS on the recipient device.
Read more about length of SMS messages
Use the SMS length calculator to count characters in your SMS and estimate the cost to send SMS.
The API response you receive after making a request will be in JSON format and will indicate success (HTTP code 200) or error (HTTP code >= 400).
Example of successful API response:
{
"info": {
"campaignId": "287c1e8d-4842-4106-8fe9-4debf8855743",
"totalPhoneNumbers": 1,
"totalValid": 1,
"totalInvalid": 0,
"totalCost": 0.041,
"totalParts": 1,
"dlrCallbackUrl": "https://mycallbackurl/endpoint",
"phoneNumbersByCountry": {
"NL": 1
},
"scheduled": false
},
"data": [
{
"msgId": "287c1e8d-4842-4106-8fe9-4debf8855743",
"status": "ACCEPTED",
"createdAt": "2022-07-10 12:12:10",
"cost": 0.041,
"to": "+3161246933x",
"countryIso": "NL",
"from": "InfoText",
"text": "Your confirmation code is 7791",
"parts": 1,
"textAnalysis": {
"length": 30,
"unicode": false,
"parts": 1
}
}
]
}
Example of API response error:
{
"error": {
"type": "invalid_param",
"message": "The parameter 'text' is empty or not set",
"uri": "https://sms.cx/docs/api/errors",
"code": 1107
}
}
Now that we have provided the request body, we must describe the authorization credentials in the request header.
As mentioned above, SMS Connexion's SMS API supports two methods of authentication (via an Access Token or via an API Key). Below are examples of PHP code for both methods of authentication, so you can choose the one you like best.
Send SMS with PHP (authentication via API Key)
The following PHP code can be used to send SMS using our SMS API with API Key. With this method of authentication, the API Key will be sent in the "X-API-KEY" custom header when an API request is made.
Copy the API Key you created at point 2.1 above and use it in the code below.
<?php
//Insert your API KEY here
$apiKey = 'YOUR_API_KEY';
//Message details
$data = [
'to' => '+316124693xx',
'from' => 'InfoText',
'text' => 'Your confirmation code is 5443',
];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.sms.cx/sms",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [
"X-API-KEY: ". $apiKey,
"Content-Type: application/json",
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
$httpCode = curl_getinfo($curl)['http_code'];
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
}
else {
if ($httpCode == 200) {
// Send SMS Success
// Parse $response object
$responseObject = json_decode($response);
echo 'SMS sent to '. $responseObject->info->totalPhoneNumbers . ' numbers '.
' with cost '. $responseObject->info->totalCost;
}
else {
// API error
// Parse error object
$responseObject = json_decode($response);
echo 'ERROR! Message: '. $responseObject->error->message .'; '.
'Type: '. $responseObject->error->type .'; '.
'Code: '. $responseObject->error->code. '; '.
'Documentation reference: '. $responseObject->error->uri;
}
}
As you'll notice, you must create and fill it with sending parameters, encode the array as an JSON object and then make an HTTP/POST call with the JSON data in the body of the call and the authorization credentials in the header.
See complete list of API error codes for this endpoint and the schema of an API success response.
Send SMS with PHP (authentication via Application ID & Secret)
Below is a sample PHP code that sends SMS with our SMS API using Access Token. Using this method of authentication, you will first get an Access Token from the authorization server. After that, add the token as "Authorization: Bearer ACCESS_TOKEN" to the request header.
Note: This is a much safer and more powerful authentication system than the API Key, mostly because it lets you set up scopes that give access to different resources of the API and because the access token is revoked (it expires) after a certain amount of time (1 day or 1 week), making it harder for attackers to use it again.
Copy the Application ID & Application Secret you created at point 2.2 above and insert them in the code below.
<?php
//Insert your Application ID and Application Secret here
$applicationId = 'YOUR_APPLICATION_ID';
$applicationSecret = 'YOUR_APPLICATION_SECRET';
function getAccessToken($applicationId, $applicationSecret) {
$curl = curl_init();
$body = [
'grant_type' => 'client_credentials',
//Optional parameter. If left empty, all scopes are granted
//'scope' => 'sms groups templates optouts',
];
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.sms.cx/oauth/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 5,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 5,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query($body),
CURLOPT_HTTPHEADER => [
"Authorization: Basic ".base64_encode($applicationId.":".$applicationSecret),
"Content-Type: application/x-www-form-urlencoded",
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
$httpCode = curl_getinfo($curl)['http_code'];
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
}
else {
if ($httpCode == 200) {
// Get Access Token success
// Parse $response object
$responseObject = json_decode($response);
return $responseObject->access_token;
}
else {
// API error
return false;
}
}
}
//We get an Access Token
//After getting we can cache or store it in the database
$accessToken = getAccessToken($applicationId, $applicationSecret);
//Message details
$data = [
'to' => '+316124693xx',
'from' => 'InfoText',
'text' => 'Your confirmation code is 5443',
];
//Trying to send SMS.
//If the access token is expired (API returns code HTTP 401 Unauthorized), we get a new one
try {
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.sms.cx/sms",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer ".$accessToken,
"Content-Type: application/json",
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
$httpCode = curl_getinfo($curl)['http_code'];
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
}
else {
if ($httpCode == 200) {
// Send SMS Success
// Parse $response object
$responseObject = json_decode($response);
echo 'SMS sent to '.$responseObject->info->totalPhoneNumbers.' numbers '.
' with cost '. $responseObject->info->totalCost;
}
elseif ($httpCode == 401) {
throw new Exception('Invalid access token');
}
else {
// API error
// Parse error object
$responseObject = json_decode($response);
echo 'ERROR! Message: '. $responseObject->error->message .'; '.
'Type: '. $responseObject->error->type .'; '.
'Code: '. $responseObject->error->code. '; '.
'Documentation reference: '. $responseObject->error->uri;
}
}
}
catch (\Exception $e) {
$accessToken = getAccessToken($applicationId, $applicationSecret);
if (!$accessToken) {
echo 'Could not get Access Token. Invalid Application ID & Secret';
}
//Here will be code to retry SMS sending with the new $accessToken
}
We created a function getAccessToken that will connect with the authorization server and get an access token.
If the API response is HTTP status code 401 (Unauthorized) when we attempt to send an SMS, it indicates that our old access token has expired. Thus, we retry sending the SMS using the new access token obtained with the above mentioned function.
Send your first SMS message
Use the command below to run the code and send your test SMS message:
$ php send-sms.php
How to send SMS to multiple phone numbers using php?
Our advanced SMS API supports sending SMS to multiple numbers with one single API request (up to 25.000 numbers at once).
In your PHP code simply assign the to variable as an array with multiple phone numbers:
//Send Bulk SMS to multiple phone numbers
$data = [
'to' => [
'+3161246933x',
'+35841264913x',
'+30691270616x',
'+4178180274x',
'+3161229912x',
'+44740087335x',
'+3620190819x',
'+3461288772x',
],
'from' => 'InfoText',
'text' => 'Your confirmation code is 5443',
];
The above code will send the same SMS message to a list of phone numbers.
If you want to send different SMS messages to many numbers and with just one single API request using PHP, the SMS API supports multiple send objects:
$data = [
[
'to' => ['+3161246933x' ,'+35841264913x', '+30691270616x'],
'from' => 'InfoText',
'text' => 'Use Promo code SUMMER20 for 20% discount on clothingsite.com',
],
[
'to' => '+44740087335x',
'from' => 'InfoText',
'text' => 'Confirm action with code 77411',
],
[
'to' => '+3161229912x',
'from' => 'InfoText',
'text' => 'Use code 477159 to verify your transaction',
],
[
'to' => '+3620190819x',
'from' => 'InfoText',
'text' => 'Your confirmation code is 15880',
],
[
'to' => '+4178180274x',
'from' => 'InfoText',
'text' => 'Your confirmation code is 22699',
],
];
You can check all available request body parameters, specifications and more examples in the API documentation - Send SMS endpoint.
If you have any queries or concerns, you can contact SMS Connexion support, where our agents will assist you in any way they can.
Additional resources: Visit the page SMS API documentation for our complete documentation, including code examples in PHP and all other popular programming languages.