PHP is a globally-used open source to do multiple functions in scripting language, which can be embedded in HTML and is very suitable for Web development. This blog mainly introduces how to make use of the php-mqtt/client client library in PHP projects to make the functions of connection, subscription, unsubscribing, message receiving and sending between Mqtt client and server.
What is MQTT?
Message Queuing Telemetry Transport is a communicative message protocol for restricted networks and IoT machines with extremely high latency. Because Message Queuing Telemetry Transport is concentrated in low bandwidth, high latency environments, it is an ideal protocol for machine-to-machine communication. MQTT is used in IoT and IIoT up to the connection of the cloud ecosystem.
What is PHP?
PHP is a server-side scripting programming language. that is used to create Static websites, Dynamic websites, and Web applications. PHP stands for Hypertext Preprocessor, which earlier stood for Personal Home Pages.
How do we do MQTT clients library selection?
This blog chooses the library php-mqtt/client, which has the highest installs on composer. MQTT communicative messages belong to network communication cases outside the HTTP system. Due to the restriction of PHP characteristics, using the extensions for network controls such as Swoole/Workerman in the PHP device can bring a better experience. The relevant MQTT client libraries are as follows:
- workerman/mqtt
- simps/mqtt
How do we do project initialization?
This project uses 7.4.21 for development. Readers can confirm their PHP with the below command.
php --version
PHP 7.4.21 (cli) (built: Jul 12 2021 11:52:30) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.21, Copyright (c), by Zend Technologies
How to use composer to install php-mqtt/client?
Composer is a dependency management option for PHP, which can control all the dependencies your PHP project requirements.
composer require php-mqtt/client
How is PHP-MQTT usage?
The server access information is as given below:
- roker: broker.emqx.io
- TCP Port: 1883
- SSL/TLS Port: 8883
Import composer autoload file and php-mqtt/client
require('vendor/autoload.php');
use \PhpMqtt\Client\MqttClient;
Set MQTT Broker connection parameters
Set the MQTT Broker communication address, port, and topic. At the same time, we call the PHP rand function to create the MQTT client id.
$server = 'broker.emqx.io';
$port = 1883;
$clientId = rand(5, 15);
$username = 'emqx_user';
$password = null;
$clean_session = false;
Write about MQTT connection function?
Use the above units to communicate, and set the communication units through ConnectionSettings, such as:
$connectionSettings = new ConnectionSettings();
$connectionSettings
->setUsername($username)
->setPassword(null)
->setKeepAliveInterval(60)
->setLastWillTopic('emqx/test/last-will')
->setLastWillMessage('client disconnect')
->setLastWillQualityOfService(1);
How to subscribe?
Program to subscribe to the heading of emqx/test, and configure a callback program for the subscription to process the received message. Here we print out the topic and communication obtained from the subscription:
$mqtt->subscribe('emqx/test', function ($topic, $message) {
printf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
How to Publish?
Construct a payload and call the publish function to upload messages to the emqx/test topic. After uploading, the client needs to enter the polling status to process the incoming communications and the retransmission queue:
for ($i = 0; $i< 10; $i++) {
$payload = array(
'protocol' => 'tcp',
'date' => date('Y-m-d H:i:s'),
'url' => 'https://github.com/emqx/MQTT-Client-Examples'
);
$mqtt->publish(
// topic
'emqx/test',
// payload
json_encode($payload),
// qos
0,
// retain
true
);
printf("msg $i send\n");
sleep(1);
}
// The client loop to process incoming messages and retransmission queues
$mqtt->loop(true);
Server connection, message uploading and receiving code.
<?PHP
require('vendor/autoload.php');
use \PhpMqtt\Client\MqttClient;
use \PhpMqtt\Client\ConnectionSettings;
$server = 'broker.emqx.io';
$port = 1883;
$clientId = rand(5, 15);
$username = 'emqx_user';
$password = null;
$clean_session = false;
$connectionSettings = new ConnectionSettings();
$connectionSettings
->setUsername($username)
->setPassword(null)
->setKeepAliveInterval(60)
->setLastWillTopic('emqx/test/last-will')
->setLastWillMessage('client disconnect')
->setLastWillQualityOfService(1);
$mqtt = new MqttClient($server, $port, $clientId);
$mqtt->connect($connectionSettings, $clean_session);
printf("client connected\n");
$mqtt->subscribe('emqx/test', function ($topic, $message) {
printf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
for ($i = 0; $i< 10; $i++) {
$payload = array(
'protocol' => 'tcp',
'date' => date('Y-m-d H:i:s'),
'url' => 'https://github.com/emqx/MQTT-Client-Examples'
);
$mqtt->publish(
// topic
'emqx/test',
// payload
json_encode($payload),
// qos
0,
// retain
true
);
printf("msg $i send\n");
sleep(1);
}
$mqtt->loop(true);
How to Test?
After executing the MQTT message uploading code, we will view that the client has perfectly connected, and the messages have been upload one by one and received successfully:
php pubsub_tcp.php
If you have any doubts about the above topic or have to get services and consultations and get the PHP and MQTT services. Feel free to contact us. AIRO GLOBAL SOFTWARE will be your strong digital partner. E-mail id: [email protected].
Author - Johnson Augustine
Chief Technical Director and Programmer
Founder: Airo Global Software Inc
LinkedIn Profile: www.linkedin.com/in/johnsontaugustine/