Home Backend Development PHP Tutorial MQTT message subscription and publishing practice in PHP development

MQTT message subscription and publishing practice in PHP development

Jul 08, 2023 pm 02:02 PM
mqtt news release Message subscription

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:

  1. Download and install an MQTT server, such as Mosquitto.
  2. 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:

  1. 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
    Copy after login
  2. 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 = ''; // 密码
    Copy after login
  3. Subscription for MQTT messages:
    To subscribe to a topic in PHP, you can use the subscribe 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";
    }
    Copy after login
  4. Publishing of MQTT messages:
    To publish a message in PHP, you can use the publish 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);
    }
    Copy after login

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 .

  1. Scenario description:
    Suppose we have a temperature sensor device that publishes real-time temperature through the MQTT protocol to the channel with the topic temperature. 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.
  2. 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界面上
}
Copy after login
  1. 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>温度监控</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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Fault tolerance and security considerations of MQTT in PHP development Fault tolerance and security considerations of MQTT in PHP development Jul 08, 2023 am 11:34 AM

Overview of fault tolerance and security considerations of MQTT in PHP development: MQTT (MessageQueuingTelemetryTransport) is a lightweight communication protocol that is widely used in the Internet of Things and machine-to-machine (M2M) communication. Using MQTT in PHP development can achieve functions such as real-time messaging and remote control. This article will introduce fault tolerance and security issues that need to be considered when using MQTT in PHP development, and provide some code examples for reference. 1. Fault tolerance

How to add real-time user chat functionality to your website using PHP and MQTT How to add real-time user chat functionality to your website using PHP and MQTT Jul 08, 2023 pm 07:46 PM

How to use PHP and MQTT to add real-time user chat function to the website. In today's Internet era, website users increasingly need real-time communication and communication. In order to meet this demand, we can use PHP and MQTT to add real-time user chat function to the website. This article will introduce how to use PHP and MQTT to implement the real-time user chat function of the website and provide code examples. Make sure the environment is ready Before starting, make sure you have installed and configured the PHP and MQTT runtime environments. You can use integrated development such as XAMPP

PHP MQTT Client Development Guide PHP MQTT Client Development Guide Mar 27, 2024 am 09:21 AM

MQTT (MessageQueuingTelemetryTransport) is a lightweight message transmission protocol commonly used for communication between IoT devices. PHP is a commonly used server-side programming language that can be used to develop MQTT clients. This article will introduce how to use PHP to develop an MQTT client and include the following content: Basic concepts of the MQTT protocol Selection and usage examples of the PHPMQTT client library: Using the PHPMQTT client to publish and

Best practices for real-time data analysis using PHP and MQTT Best practices for real-time data analysis using PHP and MQTT Jul 08, 2023 pm 05:57 PM

Best practices for real-time data analysis using PHP and MQTT With the rapid development of IoT and big data technology, real-time data analysis is becoming more and more important in various industries. In real-time data analysis, MQTT (MQTelemetryTransport), as a lightweight communication protocol, is widely used in the field of Internet of Things. Combining PHP and MQTT, real-time data analysis can be achieved quickly and efficiently. This article will introduce best practices for real-time data analysis using PHP and MQTT, and

Build a real-time chat application using PHP and MQTT Build a real-time chat application using PHP and MQTT Jul 08, 2023 pm 03:18 PM

Building a real-time chat application using PHP and MQTT Introduction: With the rapid development of the Internet and the popularity of smart devices, real-time communication has become one of the essential functions in modern society. In order to meet people's communication needs, developing a real-time chat application has become the goal pursued by many developers. In this article, we will introduce how to use PHP and MQTT (MessageQueuingTelemetryTransport) protocol to build a real-time chat application. what is

PHP implementation solution comparison and selection guide for MQTT protocol PHP implementation solution comparison and selection guide for MQTT protocol Jul 08, 2023 pm 10:43 PM

PHP implementation comparison and selection guide for the MQTT protocol Summary: MQTT (MessageQueuingTelemetryTransport) is a lightweight publish/subscribe communication protocol suitable for low-bandwidth, high-latency environments such as the Internet of Things. This article will explore the implementation of the MQTT protocol in PHP and provide a comparison and selection guide. Introduction: With the rapid development of the Internet of Things, more and more devices require real-time data transmission and communication. MQTT as a lightweight

How does PHP continue to listen to Redis message subscriptions and handle asynchronous tasks? How does PHP continue to listen to Redis message subscriptions and handle asynchronous tasks? Sep 05, 2023 pm 03:28 PM

How does PHP continue to listen to Redis message subscriptions and handle asynchronous tasks? In PHP development, we often face scenarios of processing asynchronous tasks. As a high-performance in-memory database, Redis provides a Pub/Sub mechanism that can be used to publish and subscribe to messages. This article will introduce how to use PHP to continuously listen to Redis message subscriptions, and demonstrate how to handle asynchronous tasks through code examples. Understand the Pub/Sub mechanism of Redis. Before starting, we first need to understand the Pub/Sub mechanism of Redis.

Technical guide for remote device control using PHP and MQTT Technical guide for remote device control using PHP and MQTT Jul 08, 2023 pm 05:09 PM

Technical Guide to Remote Device Control Using PHP and MQTT Introduction: The rapid development of modern technology has made the Internet of Things (IoT) gradually become a reality. In the Internet of Things, by connecting various devices through the Internet, we can achieve remote control and monitoring of the devices. MQTT is a lightweight message transfer protocol that can facilitate communication between devices. This article will introduce how to use PHP and MQTT protocols to achieve remote device control. 1. Preparation: Before starting, we need to install the MQTT server and PH

See all articles