Send SMS with PHP - Examples and Complete Guide
PHP code samples for integration with the LabsMobile SMS API
Below are the examples of programming code in PHP language to send SMS messages through the API of the LabsMobile platform.
This documentation is designed for you to connect your applications with the LabsMobile platform and automate the sending of SMS messages. The main objective of the integration of these applications is the sending of SMS messages and related communications.
Advice We recommend using our API SMS http/POST in JSON format for any integration with the LabsMobile platform. But we have other API versions that you can use depending on your environment and requirements.
With these examples you will be able to perform the integration of the following functionalities:
- Send SMS messages individually or in bulk.
- Check your account balance.
- Receive delivery confirmation and/or error notifications corresponding to the messages sent.
- Obtain notification and data of the messages received in the virtual numbers contracted.
To be taken into account
The LabsMobile API SMS uses a common base URL for all requests: https://api.labsmobile.com
.
It is highly recommended to use a URL that includes the HTTPS
protocol in any version of the API.
Authentication is done with the username and an API token, myUsername:myToken
. You must create the API token from the API Settings section of your account.
PHP Library for SMS Sending
Our recommendation is to integrate SMS sending into your PHP application LabsMobile PHP Library due to its simplicity, ease and speed of integration.
The prerequisites for installing the LabsMobile PHP library are to have a PHP version 5.4 or higher installed and the necessary libraries (cURL and JSON). You can install the library via Composer labsmobile/sms-php
or manually.
<?php require __DIR__ . '/../vendor/autoload.php'; use Labsmobile\SmsPhp\LabsMobileClient; use Labsmobile\SmsPhp\LabsMobileModelTextMessage; use Labsmobile\SmsPhp\Exception\RestException; class LabsMobileSendSms { public $username = 'myUsername'; public $token = 'myToken'; public function sendSms() { try { $message = 'Your verification code is 123'; $phone = ['12015550123']; $labsMobileClient = new LabsMobileClient($this->username, $this->token); $bodySms = new LabsMobileModelTextMessage($phone,$message); $bodySms->setScheduled("2024-12-02 09:00:00"); $bodySms->setLong(1); $labsMobileClient = $labsMobileClient->sendSms($bodySms); $body = $labsMobileClient->getBody(); $json = json_decode($body); echo 'Status ', $json->code . " " . $json->message; } catch (RestException $exception) { echo 'Error ', $exception->getStatus() ." ". $exception->getMessage(); } } } $smsSender = new LabsMobileSendSms(); $smsSender->sendSms();
More information about requirements, installation, parameters and functionalities:
Send SMS with http/POST
Here is an example of code in PHP language to send SMS messages using the API SMS http/POST that uses the JSON
format for the information exchange variables.
As you can see, you need to create a structure in JSON
format containing all the necessary parameters for sending and make a HTTP/POST
call with this data in the body of the request.
<?php $auth_basic = base64_encode("myUsername:myToken"); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.labsmobile.com/json/send", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => '{ "message":"Your verification code is 123", "tpoa":"Sender", "recipient": [ { "msisdn":"12015550123" } ] }', CURLOPT_HTTPHEADER => array( "Authorization: Basic ".$auth_basic, "Cache-Control: no-cache", "Content-Type: application/json" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; }
<?php $auth_basic = base64_encode("myUsername:myToken"); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.labsmobile.com/json/send", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => '{ "message":"Do not miss our Sale! Use code XXXX123 for 20% off.", "tpoa":"Sender", "recipient": [ { "msisdn":"12015550123" }, { "msisdn":"12015550124" }, { "msisdn":"12015550125" } ] }', CURLOPT_HTTPHEADER => array( "Authorization: Basic ".$auth_basic, "Cache-Control: no-cache", "Content-Type: application/json" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; }
{ "subid": "65f33a88ceb3d", "code": "0", "message": "Message has been successfully sent." }
{ "subid": "65f7f7041385d", "code": "35", "message": "The account has no enough credit for this sending" }
All error codes can be found in API documentation, error codes.
For more details on the available parameters and configuration options, see the official documentation at:
Send SMS with http/GET
This is an example of code in PHP language to send SMS messages using the SMS API http/GET
.
As you can see, you must pass a series of GET
variables in the same URL and make a HTTP
call. It is important to encode all values as URL using the urlencode()
function.
Important The SMS http/GET API transmits credentials (username and API token) unencrypted and unsecured. We recommend using this API GET
only when absolutely essential and use the API SMS http/POST instead.
<?php $curl = curl_init(); $username = "myUsername"; $token = "myToken"; $msisdn = array(12015550123); $message = "Don't miss our Sale! Use code XXXX123 for 20% off."; $url = 'https://api.labsmobile.com/get/send.php?'; $url .= 'username='. urlencode($username) .'&'; $url .= 'password='. urlencode($token) .'&'; $url .= 'msisdn=' . urlencode(json_encode($msisdn)) .'&'; $url .= 'message=' . urlencode($message); curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'GET', )); $response = curl_exec($curl); curl_close($curl); echo $response;
<?php $curl = curl_init(); $username = "myUsername"; $token = "myToken"; $msisdn = array(12015550123,12015550124,12015550125); $message = "Don't miss our Sale! Use code XXXX123 for 20% off."; $url = 'https://api.labsmobile.com/get/send.php?'; $url .= 'username='. urlencode($username) .'&'; $url .= 'password='. urlencode($token) .'&'; $url .= 'msisdn=' . urlencode(json_encode($msisdn)) .'&'; $url .= 'message=' . urlencode($message); curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'GET', )); $response = curl_exec($curl); curl_close($curl); echo $response;
{ "subid": "65f33a88ceb3d", "code": "0", "message": "Message has been successfully sent." }
{ "subid": "65f7f7041385d", "code": "35", "message": "The account has no enough credit for this sending" }
All error codes can be found in API documentation, error codes.
For more details on the available parameters and configuration options, see the official documentation at:
Account balance inquiry
With this code example in PHP
you can consult your account balance using the API SMS
of LabsMobile.
Through a call to this endpoint, you can get information about the amount of credits available in your LabsMobile account. The connection is established through a HTTP/GET
request with authentication in the HTTP
connection header.
<?php $auth_basic = base64_encode("myUsername:myToken"); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.labsmobile.com/json/balance", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array( "Authorization: Basic ".$auth_basic, "Cache-Control: no-cache", ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; }
{"code":0,"credits":"10"}
See the complete documentation at:
Receive status of sent messages
This example script receives a call from the LabsMobile platform when a sent SMS message changes status. To implement this solution, it is essential to configure the appropriate parameters, the confirmation URL in the ackurl
parameter in the request or the default URL in the API Settings of your account.
Therefore, it is necessary to publish a script like this in your system so that our platform calls the URL when a status change occurs in any of the sent messages.
The example code obtains the URL parameters using the global $_GET
variable and then assigns these parameters to local variables.
<?php $app = function () { $queryParams = $_GET; $acklevel = $queryParams['acklevel'] ?? null; $credits = $queryParams['credits'] ?? null; $msisdn = $queryParams['msisdn'] ?? null; $status = $queryParams['status'] ?? null; $subid = $queryParams['subid'] ?? null; $timestamp = $queryParams['timestamp'] ?? null; echo "Variable acklevel: $acklevel\n"; echo "Variable credits: $credits\n"; echo "Variable msisdn: $msisdn\n"; echo "Variable status: $status\n"; echo "Variable subid: $subid\n"; echo "Variable timestamp: $timestamp\n"; }; $app();
See the complete documentation at:
Receiving SMS messages with PHP
Once you have contracted a virtual number, you will be able to receive messages via API
on a specific URL via a HTTP/GET
call to a script in your system. Each message received will invoke the URL, transmitting all its data in variables in JSON
format.
To activate this functionality you must inform the URL for receiving messages in the Settings of your account.
It is necessary to configure an endpoint in your system so that the LabsMobile platform calls this script when an SMS is received on any of the contracted virtual numbers.
The example code obtains the URL parameters using the global variable $_GET
and then assigns these parameters to local variables.
<?php $app = function () { $queryParams = $_GET; $inbound_number = $queryParams['inbound_number'] ?? null; $service_number = $queryParams['service_number'] ?? null; $msisdn = $queryParams['msisdn'] ?? null; $message = $queryParams['message'] ?? null; $timestamp = $queryParams['timestamp'] ?? null; echo "Variable inbound_number: $inbound_number\n"; echo "Variable service_number: $service_number\n"; echo "Variable msisdn: $msisdn\n"; echo "Variable message: $message\n"; echo "Variable timestamp: $timestamp\n"; }; $app();
See the complete documentation at:
Start Sending SMS with PHP Now
Sending SMS from your PHP application is easy and fast. Follow these simple steps to create your account, prepare the environment, and start sending messages to your customers using the LabsMobile API.
Step 1: Create your LabsMobile Account
Sign up for free. Visit the official LabsMobile page: Create account. Confirm your account via the verification email you will receive.
Access your Control Panel. Log in with your username and password. Go to the “API Configuration” section to obtain your API token, necessary to integrate your PHP application.
Step 2: Choose an integration method
Select from:
- PHP Library (recommended)
- http/POST API
- http/GET API
- Mail API
Check out and adapt the sample code you can find on this page.
Step 3: Send your First SMS
Add credentials. Customize the PHP code with your account's username and API token.
Create and Customize your Message. Define the destination number, the sender, and the content of the message. Optionally activate the simulated mode to avoid consuming credits with your first sends. Check all the sending options and parameters on the documentation page of the chosen integration method.
Send and Verify. Send the message and check the status in the control panel (in the History section) to confirm its correct delivery.
Benefits of Using PHP to Send SMS
Integrating SMS sending into applications developed in PHP offers multiple advantages for companies and projects in various sectors. PHP, as a widely used programming language, allows you to create effective messaging systems with ease. Below, we explore the main benefits of using PHP to send SMS, organized into key subsections:
- Simple and Fast Integration. PHP allows direct integration with SMS sending services through APIs and specialized libraries. This simplifies development and avoids complex configurations. Applications can start sending messages in just a few steps, reducing implementation times.
- Instant Communication. The integration of SMS with PHP allows real-time notifications, without depending on an Internet connection by the end user. This guarantees that messages such as alerts, appointment reminders and order confirmations arrive instantly.
- Process Automation. PHP facilitates the automation of SMS sending through event-based programming. For example, automatic messages can be generated when a purchase is made, a password recovery is requested or an appointment is scheduled. This reduces the operational load and ensures more efficient management.
- Message Personalization. PHP applications can generate personalized messages using data stored in databases. This allows for sending communications tailored to each user, improving the customer experience and increasing the effectiveness of promotional campaigns and service notifications.
- Scalability and Flexibility. From sending individual messages to mass campaigns, PHP allows for flexible management of SMS sending. This makes it suitable for both small businesses and large organizations that need to manage a high volume of messages.
- Security and Data Protection. It is possible to implement secure connections using HTTPS protocols, ensuring that data transmission is secure. In addition, it is possible to use SMS for two-factor authentication (2FA), improving the security of accounts and transactions.
- Cost Effective. Using SMS as a communication channel is cost-effective and offers an excellent return on investment. PHP allows for centralizing message management, reducing operating costs by automating processes and minimizing the need for human resources.
- Technical Support and Active Community. This language has a global developer community that offers ongoing support. This includes detailed documentation, active forums, and open source libraries that help you deploy SMS services quickly and efficiently.
Take advantage of all these benefits by integrating SMS sending into your PHP applications. Improve communication with your users and automate your processes with a secure, flexible and cost-effective solution.
Support resources
We recommend that you consult and take into account the following support resources in your integration:
- Description, manual and code examples of the SMS sending API.
- Technical guide to an OTP validation or authentication process by SMS.
- All LabsMobile API versions and functionalities.
- First Steps to API Integration Tutorial
- Create a demo account
- Recommendations and best practices in any integration.
- Plugins, modules and extensions.
- Need help? Contact our technicians