


MQTT message subscription and publishing practice in PHP development
MQTT's practical message subscription and publishing in PHP development
Introduction:
With the development of the Internet of Things, the Message Queuing Telemetry Transport Protocol (MQTT) communicates between sensor devices and back-end applications plays an important role in. As a lightweight protocol, MQTT has the characteristics of low energy consumption, high reliability and scalability. In PHP development, MQTT is used to subscribe and publish messages, which can easily communicate with sensor devices and transmit data to the back-end application for processing and display. This article will introduce the practical application of MQTT in PHP development and provide relevant code examples.
1. Introduction to MQTT:
MQTT is a message queue transmission protocol based on the publish/subscribe model. It adopts a lightweight binary message format and is suitable for various hardware devices such as sensors and embedded systems. The MQTT protocol mainly contains two roles: message publisher and message subscriber. Publishers publish messages to a specific topic, while subscribers subscribe to topics of interest to receive relevant messages. The MQTT protocol also supports message QoS (Quality of Service) level settings to ensure data reliability.
2. Install MQTT server:
Before starting the actual MQTT in PHP development, we need to build an MQTT server first. The following are brief steps to build an MQTT server:
- Download and install an MQTT server, such as Mosquitto.
- Run the MQTT server, the default listening port is 1883.
3. Using MQTT in PHP:
The process of using MQTT for message subscription and publishing in PHP is as follows:
-
Introduce the MQTT client library :
First, you need to introduce the MQTT client library. Commonly used MQTT client libraries in PHP include phpMQTT and mosquitto-php. This article takes phpMQTT as an example, which can be installed through composer:composer require bluerhinos/phpmqttclient
-
MQTT client configuration:
Before performing MQTT operations in PHP code, you need to configure the connection first, including the server Address, port number, QoS level, etc. The following is an example configuration:$mqttServer = 'localhost'; // MQTT服务器地址 $mqttPort = 1883; // MQTT服务器端口 $mqttClientId = 'php_script'; // 客户端ID $mqttUsername = ''; //用户名 $mqttPassword = ''; // 密码
-
Subscription for MQTT messages:
To subscribe to a topic in PHP, you can use thesubscribe
method. The following is an example:require('phpMQTT.php'); $mqtt = new phpMQTT($mqttServer, $mqttPort, $mqttClientId); if($mqtt->connect(true, NULL, $mqttUsername, $mqttPassword)) { $topics['topic_name'] = array('qos' => 0, 'function' => 'dataCallback'); $mqtt->subscribe($topics, 0); while($mqtt->proc()){ } $mqtt->close(); } else { echo "连接MQTT服务器失败!"; exit(1); } function dataCallback($topic, $payload) { echo "收到消息:$payload"; }
-
Publishing of MQTT messages:
To publish a message in PHP, you can use thepublish
method. The following is an example:require('phpMQTT.php'); $mqtt = new phpMQTT($mqttServer, $mqttPort, $mqttClientId); if($mqtt->connect(true, NULL, $mqttUsername, $mqttPassword)) { $mqtt->publish('topic_name', '消息内容', 0); $mqtt->close(); } else { echo "连接MQTT服务器失败!"; exit(1); }
4. Practical application:
The following takes a simple real-life application as an example to demonstrate the practical application of using MQTT for message subscription and publishing in PHP .
- Scenario description:
Suppose we have a temperature sensor device that publishes real-time temperature through the MQTT protocol to the channel with the topictemperature
. Our PHP application needs to receive and process this temperature data in real time, and to do this, we will subscribe to this topic and display the real-time temperature through the web interface. - PHP code example:
Subscribe temperature data and display it on the Web interface:
require('phpMQTT.php'); $mqttServer = 'localhost'; // MQTT服务器地址 $mqttPort = 1883; // MQTT服务器端口 $mqttClientId = 'php_script'; // 客户端ID $mqtt = new phpMQTT($mqttServer, $mqttPort, $mqttClientId); if($mqtt->connect(true, NULL, NULL, NULL)) { $topics['temperature'] = array('qos' => 0, 'function' => 'temperatureCallback'); $mqtt->subscribe($topics, 0); echo "开始订阅温度数据... "; while($mqtt->proc()){ } $mqtt->close(); } else { echo "连接MQTT服务器失败!"; exit(1); } function temperatureCallback($topic, $payload) { echo "收到温度消息:$payload "; // 在这里进行温度数据的处理,如存储到数据库或展示在Web界面上 }
- Web interface example:
Display temperature data in real time through the Web interface The sample code is as follows:
<!DOCTYPE html> <html> <head> <title>温度监控</title> </head> <body> <h1 id="温度监控">温度监控</h1> <div id="temperature"></div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { var mqttServer = 'mqtt://localhost:1883'; var clientId = 'web_client'; var temperatureTopic = 'temperature'; var client = mqtt.connect(mqttServer, { clientId: clientId }); client.on('connect', function() { client.subscribe(temperatureTopic); }); client.on('message', function(topic, message) { if (topic === temperatureTopic) { var temperature = message.toString(); $('#temperature').text('当前温度:' + temperature + '℃'); } }); }); </script> </body> </html>
The above sample code demonstrates the practical application of using MQTT for message subscription and publishing in PHP. By subscribing to temperature data, we can receive temperature data in real time for processing and display, and by publishing messages, we can send control instructions to sensor devices. In actual development, the code can be expanded and adjusted according to specific needs.
Conclusion:
This article introduces the practical application of MQTT message subscription and publishing in PHP development, and provides relevant code examples. By using the MQTT protocol, PHP applications can easily communicate with sensor devices and realize real-time data transmission and processing. In IoT application development, using MQTT for messaging can improve communication efficiency and reliability, and bring convenience to application development.
The above is the detailed content of MQTT message subscription and publishing practice in PHP development. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)