PHP is a widely used open source multipurpose scripting language that can be embedded into HTML and is especially suitable for Web development.

This article mainly introduces how to use PHP-MQTT /client client library in PHP project, realize MQTT client and MQTT server connection, subscribe, unsubscribe, send and receive messages and other functions.

MQTT client library selection

This article selects the most downloaded PHP-MQTT/Client client library on Composer. More PHP-MQTT client libraries can be viewed at Packagist-Search MQTT.

See Packagist PHP-MQTT /client for more documentation on using PHP-MQTT /client.

MQTT communication belongs to the network communication scenario outside the HTTP system. Due to the limitation of PHP features, it can bring a better experience to use THE EXTENSIONS such as Swoole/Workerman in THE PHP system, which will not be described in this article. The related MQTT client libraries are as follows:

  • Workerman/MQTT: Asynchronous MQTT client for PHP based on workerman
  • Simps/MQTT: MQTT Protocol Analysis and Coroutine Client for PHP.

Project initialization

Confirming the PHP version

This project uses 7.4.21 for development testing, and the reader can confirm the version of PHP with the following command.

PHP -- Version PHP 7.4.21 (CLI) (Built-in: 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 TechnologiesCopy the code

Install the PHP-MQTT /client client using Composer

Composer is a dependency management tool for PHP that manages all the dependencies you need for your PHP project.

composer require php-mqtt/client
Copy the code

Use PHP MQTT

Connect to the MQTT server

This article will use the free public MQTT server provided by EMQ X, which is built on EMQ X’s MQTT iot cloud platform. The server information is as follows:

  • Broker: broker-cn.emqx.io
  • TCP Port: 1883
  • SSL/TLS Port: 8883

Import the Composer Autoload file and PHP-MQTT /client

require('vendor/autoload.php');

use \PhpMqtt\Client\MqttClient;
Copy the code

Set MQTT Broker connection parameters

Set the MQTT Broker connection address, port, and topic, and we call the PHP RAND function to randomly generate the MQTT client ID.

$server   = 'broker-cn.emqx.io';
$port     = 1883;
$clientId = rand(5.15);
$username = 'emqx_user';
$password = null;
$clean_session = false;
Copy the code

Write MQTT connection functions

Connect using the above parameters, and use ConnectionSettings to set the connection parameters, such as

$connectionSettings  = new ConnectionSettings();
$connectionSettings
  ->setUsername($username)
  ->setPassword(null)
  ->setKeepAliveInterval(60)
  // Last Will set
  ->setLastWillTopic('emqx/test/last-will')
  ->setLastWillMessage('client disconnect')
  ->setLastWillQualityOfService(1);
Copy the code

Subscribe to news

Write code to subscribe to the EMQX /test topic and configure the callback number for the subscription to process the received messages. Here we print out the subscribed topic and message:

/ / subscribe
$mqtt->subscribe('emqx/test'.function ($topic.$message) {
    printf("Received message on topic [%s]: %s\n".$topic.$message);
}, 0);
Copy the code

news

A payload is constructed and a publish function is called to publish messages to the EMqx /test topic. After the publication is complete, the client needs to enter the polling state to process the incoming messages and resend the 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 polls to process incoming messages and the resend queue
$mqtt->loop(true);
Copy the code

The complete code

Server connection, message publishing, and receiving codes.


      

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)
  // Last Will set
  ->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);

Copy the code

test

Running the MQTT message publishing code, we will see that the client has successfully connected and the messages have been published and received successfully one by one:

php pubsub_tcp.php
Copy the code

conclusion

At this point, we have completed the connection to the public MQTT server using the PHP-MQTT /client client and implemented the connection, message publishing, and subscription of the test client to the MQTT server.

Copyright notice: this article is the original EMQ, reprint please indicate the source.

Link: www.emqx.com/zh/blog/how…