search
HomeBackend DevelopmentPHP TutorialOne article to quickly understand how to use MQTT in PHP projects

One article to quickly understand how to use MQTT in PHP projects

#PHP is a widely used open source multi-purpose scripting language that 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 a PHP project to implement MQTT client and MQTT serverConnect, subscribe, unsubscribe, send and receive messages and other functions.

MQTT client library selection

This article selects the client library with the highest download volume php-mqtt/client on composer, more The PHP-MQTT client library can be viewed in Packagist - Search MQTT.

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

MQTT communication belongs to network communication scenarios outside the HTTP system. Due to the limitations of PHP features, using Swoole/Workerman and other extensions specifically designed for network communication in the PHP system can bring a better experience. This article uses Without going into details, 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 use the following command to confirm the PHP version.

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 the php-mqtt/client client

Composer is a dependency management tool for PHP that can manage all the dependencies required by your PHP project relation.

composer require php-mqtt/client

PHP MQTT Use

to connect to the MQTT server

This article will use the free public MQTT provided by EMQ X Server, this service is created based on EMQ X's MQTT IoT cloud platform. The server access information is as follows:

  • Broker: broker-cn.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;

settings MQTT Broker connection parameters

Set the MQTT Broker connection address, port and topic. At the same time, 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;

Write MQTT connection function

Use the above parameters to connect, and set the connection parameters through ConnectionSettings, such as

$connectionSettings  = new ConnectionSettings();$connectionSettings
  ->setUsername($username)
  ->setPassword(null)
  ->setKeepAliveInterval(60)  // Last Will 设置
  ->setLastWillTopic('emqx/test/last-will')
  ->setLastWillMessage('client disconnect')
  ->setLastWillQualityOfService(1);复制代码

Subscribe to the message

Write code to subscribe to the emqx/test topic, and configure the callback function for the subscription to process the received message. Here we will subscribe to the obtained topic And the message is printed out:

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

Publish message

Construct a payload and call the publish function to the emqx/test topic Publish the message. After the publishing is completed, the client needs to enter the polling state to process the incoming message and resend queue:

for ($i = 0; $i< 10; $i++) {
  $payload = array(
    &#39;protocol&#39; => &#39;tcp&#39;,
    &#39;date&#39; => date(&#39;Y-m-d H:i:s&#39;),
    &#39;url&#39; => &#39;https://github.com/emqx/MQTT-Client-Examples&#39;
  );
  $mqtt->publish(
    // topic
    &#39;emqx/test&#39;,
    // payload
    json_encode($payload),
    // qos
    0,
    // retain
    true
  );
  printf("msg $i send\n");
  sleep(1);
}

// 客户端轮询以处理传入消息和重发队列
$mqtt->loop(true);

Full code

Server connection, message publishing with receiving code.

setUsername($username)
  ->setPassword(null)
  ->setKeepAliveInterval(60)
  // Last Will 设置
  ->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

Run 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

One article to quickly understand how to use MQTT in PHP projects

Summary

At this point, we have completed using the php-mqtt/client client to connect to the public MQTT Server, and implements the connection, message publishing and subscription between the test client and the MQTT server.

Original link: https://www.emqx.com/zh/blog/how-to-use-mqtt-in-php

Author: EMQ

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of One article to quickly understand how to use MQTT in PHP projects. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.