How to Send SMS through the SMPP API using PHP
The Short Message Peer-to-Peer (SMPP) API is a powerful telecommunications protocol designed for exchanging SMS messages between peer entities, such as SMS centers and external applications. This comprehensive guide demonstrates how to implement the SMPP API using PHP to connect with the Ozeki SMS Gateway, enabling developers to send and manage SMS messages efficiently. With detailed PHP code examples, this tutorial covers connection setup, message sending, delivery reports, and best practices for building a robust SMPP API client.
Understanding the SMPP API and Its Role in SMS Messaging
The SMPP API (Short Message Peer-to-Peer) is widely used in the
telecommunications industry to facilitate high-volume SMS communication. It allows
applications to connect to an SMS gateway, such as the Ozeki SMS Gateway, to send
and receive messages reliably. By leveraging PHP, developers can
create scalable applications that interact with the SMPP API to
manage SMS workflows. This guide uses the php-smpp
library, a robust
tool for implementing the SMPP protocol in PHP,
to simplify low-level protocol interactions.
PHP SMPP Client Setup to send SMS through the SMPP API
To send SMS via SMPP API, you must first setup an SMPP user, and then bind your client to the Ozeki SMS Gateway's SMPP server. We'll use the php-smpp library which provides SMPP protocol implementation:
- Install the
php-smpp
library using Composer to handle SMPP API interactions. - Configure your connection parameters, including the host, port, username, and password provided by the Ozeki SMS Gateway.
- Establish a connection to the SMPP server using a socket transport.
Here’s how to install the library:
composer require onlinecity/php-smpp
Basic Connection Example for SMPP API in PHP
The following PHP code demonstrates how to establish a connection
to the Ozeki SMS Gateway using the SMPP API. This example uses the
php-smpp
library to create a client, connect to the server, and
bind as a transmitter for sending SMS messages.
<?php require 'vendor/autoload.php'; use Smpp\Client; use Smpp\Transport\Socket; $host = 'your.ozeki.server'; $port = 2775; $username = 'your_username'; $password = 'your_password'; // Create transport and client $transport = new Socket([$host], $port); $transport->setRecvTimeout(30000); $smpp = new Client($transport); // Connect and bind $transport->open(); $smpp->bindTransmitter($username, $password); echo "Successfully connected to SMPP server\n"; // Send message here... // Close connection $smpp->close(); ?>
This code initializes a socket transport, sets a timeout for receiving data, and binds the client as a transmitter using the provided credentials. Once connected, the client is ready to send SMS messages via the SMPP API.
Maintain the connection with PHP through the SMPP API
To ensure a reliable connection to the SMPP API, your PHP
application must send periodic keep-alive messages using the enquire_link
PDU. This prevents the connection from timing out and ensures continuous operation.
Below is an example of how to implement a keep-alive mechanism in PHP.
function sendKeepAlive($smpp) { try { $smpp->enquireLink(); echo "Keep-alive sent\n"; } catch (Exception $e) { echo "Keep-alive failed: " . $e->getMessage() . "\n"; // Implement reconnection logic here } } // Send keep-alive every 30 seconds $keepAliveInterval = 30; $lastKeepAlive = time(); while (true) { if (time() - $lastKeepAlive >= $keepAliveInterval) { sendKeepAlive($smpp); $lastKeepAlive = time(); } // Handle other operations here sleep(1); }
This script sends a keep-alive message every 30 seconds and includes error handling to manage connection issues. If a keep-alive fails, you can implement reconnection logic to restore the connection to the SMPP API.
Sending SMS Messages with PHP through the SMPP API
Sending SMS messages through the SMPP API in PHP
involves creating an SMS message with the submit_sm
PDU. The following
example demonstrates how to send a message using the php-smpp
library.
use Smpp\Address; use Smpp\SMS; $from = new Address('12345', SMPP::TON_ALPHANUMERIC); $to = new Address('+1234567890', SMPP::TON_INTERNATIONAL, SMPP::NPI_ISDN); $message = new SMS($from, $to, 'Hello from PHP SMPP client!'); $message->setDataCoding(SMPP::DATA_CODING_DEFAULT); try { $messageId = $smpp->sendSMS($message); echo "Message sent successfully, ID: $messageId\n"; } catch (Exception $e) { echo "Failed to send message: " . $e->getMessage() . "\n"; }
In this example, the sender’s address is set as an alphanumeric string, and the
recipient’s number uses international formatting. The DATA_CODING_DEFAULT
setting ensures compatibility with standard text messages. Error handling ensures
that any issues during message sending are caught and reported.
Handling Delivery Reports with PHP through the SMPP API
The SMPP API supports delivery reports to track the status of
sent messages. To receive these reports in PHP, bind your client
as a receiver and process incoming deliver_sm
PDUs. The following
code shows how to implement this functionality.
// First bind as receiver to get delivery reports $smpp->bindReceiver($username, $password); while (true) { try { $pdu = $smpp->readPDU(); if ($pdu instanceof DeliverSm) { $messageId = $pdu->getReceiptedMessageId(); $status = $pdu->getMessageStatus(); echo "Delivery report for $messageId: $status\n"; // Send response $smpp->respond($pdu, new DeliverSmResp()); } } catch (Exception $e) { echo "Error reading PDU: " . $e->getMessage() . "\n"; break; } }
This code binds the client as a receiver to listen for delivery reports, processes incoming PDUs, and sends appropriate responses. This ensures that your PHP application can track message delivery statuses effectively.
Complete PHP SMPP Client for Sending SMS via the SMPP API
Below is a comprehensive PHP class that encapsulates the SMPP API functionality, including connection management, message sending, and reconnection logic. This implementation is designed for production use, with robust error handling and modularity.
<?php require 'vendor/autoload.php'; use Smpp\Client; use Smpp\Transport\Socket; use Smpp\Address; use Smpp\SMS; class SMPPClient { private $transport; private $smpp; private $config; private $isConnected = false; public function __construct($config) { $this->config = $config; $this->connect(); } public function connect() { try { $this->transport = new Socket([$this->config['host']], $this->config['port']); $this->transport->setRecvTimeout(30000); $this->smpp = new Client($this->transport); $this->transport->open(); $this->smpp->bindTransceiver( $this->config['username'], $this->config['password'] ); $this->isConnected = true; echo "Connected to SMPP server\n"; } catch (Exception $e) { echo "Connection failed: " . $e->getMessage() . "\n"; $this->reconnect(); } } public function sendSMS($from, $to, $message) { if (!$this->isConnected) { throw new Exception("Not connected to SMPP server"); } try { $fromAddr = new Address($from, SMPP::TON_ALPHANUMERIC); $toAddr = new Address($to, SMPP::TON_INTERNATIONAL, SMPP::NPI_ISDN); $sms = new SMS($fromAddr, $toAddr, $message); $sms->setDataCoding(SMPP::DATA_CODING_DEFAULT); return $this->smpp->sendSMS($sms); } catch (Exception $e) { $this->isConnected = false; throw $e; } } public function reconnect() { $this->close(); sleep(5); $this->connect(); } public function close() { if ($this->isConnected) { $this->smpp->close(); $this->isConnected = false; } } public function __destruct() { $this->close(); } } // Usage example $config = [ 'host' => 'your.ozeki.server', 'port' => 2775, 'username' => 'your_username', 'password' => 'your_password' ]; $client = new SMPPClient($config); try { $messageId = $client->sendSMS('12345', '+1234567890', 'Hello from PHP!'); echo "Message sent with ID: $messageId\n"; } catch (Exception $e) { echo "Error sending message: " . $e->getMessage() . "\n"; } ?>
This class provides a reusable PHP implementation of the SMPP API, with methods for connecting, sending messages, reconnecting on failure, and cleaning up resources. It’s designed to be modular and easy to integrate into larger applications.
Best Practices for Building a PHP SMPP Client
To ensure your PHP application using the SMPP API is robust and scalable, follow these best practices:
- Implement Robust Error Handling: Catch and handle exceptions for connection failures, message sending errors, and PDU processing issues to ensure reliability.
- Use Persistent Connections: Maintain a single connection to the SMPP API to reduce overhead and improve performance.
- Implement Message Queuing: For high-volume SMS sending, use a queue to manage message delivery and prevent server overload.
- Monitor Connection State: Continuously check the connection status and implement automatic reconnection logic to handle network disruptions.
- Use a Worker Process: Run your PHP SMPP client as a daemon or worker process for continuous operation in production environments.
- Log Activity: Implement logging to track connection events, message statuses, and errors for debugging and monitoring.
Conclusion
This comprehensive guide has demonstrated how to implement a PHP
client for the SMPP API to send and manage SMS messages using
the Ozeki SMS Gateway. By leveraging the php-smpp
library,
developers can handle low-level SMPP protocol details while
focusing on building robust applications. The provided code examples cover
connection management, message sending, delivery report handling, and a complete
PHP class for production use. For advanced applications,
consider implementing additional features such as message queuing, detailed
logging, and monitoring to enhance reliability and scalability.
For production environments, ensure your PHP SMPP client includes robust error handling, connection monitoring, and logging. The SMPP API supports advanced features like message prioritization and throttling, which can be explored as your application requirements grow.
More information
- How to set up an SMPP API client connection with Your SMSC
- How to set up an SMPP API server to send ad receive SMS from multiple Apps
- How to choose the right SMPP API provider for your business
- How to Send SMS Using the SMPP API at the protocol level
- How to Send SMS through the SMPP API using Python
- How to Send SMS through the SMPP API using Javascript
- How to send SMS through the SMPP API using Java
- How to Send SMS through the SMPP API using PHP
- How to Send SMS through the SMPP API using C#
- How to Send SMS through the SMPP API using C/Cpp
- How to Receive SMS using the SMPP API
- How to Receive an SMS Delivery Report using the SMPP API
- SMPP API FAQ