DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Use MQTT in PHP
  • Inheritance in PHP: A Simple Guide With Examples
  • OPC-UA and MQTT: A Guide to Protocols, Python Implementations
  • The Blue Elephant in the Room: Why PHP Should Not Be Ignored Now or Ever

Trending

  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • How to Build Local LLM RAG Apps With Ollama, DeepSeek-R1, and SingleStore
  • What Is Plagiarism? How to Avoid It and Cite Sources
  • Scalable, Resilient Data Orchestration: The Power of Intelligent Systems
  1. DZone
  2. Data Engineering
  3. IoT
  4. How to Use MQTT in PHP

How to Use MQTT in PHP

This article mainly introduces how to use the php-mqtt/client client library in PHP projects.

By 
Li Guowei user avatar
Li Guowei
·
Oct. 07, 22 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
8.2K Views

Join the DZone community and get the full member experience.

Join For Free

PHP is a widely-used open-source multi-purpose scripting language, which can be embedded in HTML and is especially suitable for Web development.

This article mainly introduces how to use the php-mqtt/client client library in PHP projects to implement the functions of connection, subscription, unsubscribing, message receiving and sending between MQTT client and MQTT server.

MQTT Client Library Selection

This article chooses the client library php-mqtt/client, which has the highest downloads on composer. For more PHP-MQTT client libraries, please view in Packagist-Search MQTT.

For more documentation about php-mqtt/client, please refer to Packagist php-mqtt/client.

MQTT communication belongs to a network communication scenario outside the HTTP system. Due to the limitation of PHP characteristics, using extensions for network communication such as Swoole/Workerman in the PHP system can bring a better experience. Its use will not be repeated in this article. The relevant 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

Confirm PHP Version

This project uses 7.4.21 for development and testing. Readers can confirm the PHP version with the following 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

Use Composer to Install php-mqtt/client

Composer is a dependency management tool for PHP, which can manage all the dependencies your PHP project needs.

composer require php-mqtt/client

PHP MQTT Usage

Connect to MQTT Server

This article will use the Free Public MQTT Server provided by EMQX, which is created on EMQX's MQTT Cloud Service. The server access information is as follows:

  • Broker: 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 connection address, port, and topic. At the same time, we call the PHP rand function to generate the MQTT client ID randomly.

$server   = 'broker.emqx.io';
$port     = 1883;
$clientId = rand(5, 15);
$username = 'emqx_user';
$password = null;
$clean_session = false;

Write MQTT Connection Function

Use the above parameters to connect, and set the connection parameters through ConnectionSettings, like this:

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

Subscribe

Program to subscribe to the topic of emqx/test, and configure a callback function for the subscription to process the received message. Here we print out the topic and message obtained from the subscription:

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

Publish

Construct a payload and call the publish function to publish messages to the emqx/test topic. After publishing, the client needs to enter the polling status to process the incoming messages 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);

Complete Code

The server connection and message publishing and receiving code is as follows:

 
<?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);

Test

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

php pubsub_tcp.php

PHP MQTT Test

Summary

So far, we have used the php-mqtt/client to connect to the public MQTT server, and implemented the connection, message publishing, and subscription between the test client and the MQTT server.

MQTT PHP

Published at DZone with permission of Li Guowei. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Use MQTT in PHP
  • Inheritance in PHP: A Simple Guide With Examples
  • OPC-UA and MQTT: A Guide to Protocols, Python Implementations
  • The Blue Elephant in the Room: Why PHP Should Not Be Ignored Now or Ever

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!