search
HomeBackend DevelopmentPHP TutorialCommunication and control of the Internet of Things using PHP and MQTT

With the development of Internet of Things technology, more and more devices and items are becoming connected to the Internet, and communication and control between these devices and items are required. This article will introduce how to use PHP and MQTT protocols to implement communication and control of the Internet of Things.

1. What is the MQTT protocol

MQTT (Message Queuing Telemetry Transport) is a lightweight message transmission protocol that is implemented based on the publish/subscribe model. The MQTT protocol can be used in low-bandwidth and unreliable network environments and is a protocol suitable for IoT devices.

The basic concepts of the MQTT protocol are:

  • Client: a device or application that can connect to the MQTT server and publish or subscribe to messages.
  • Server (Broker): MQTT message broker, responsible for receiving, storing and forwarding messages.
  • Topic: Represents the category or name of a message. Topics can consist of one or more words, separated by "/". For example, the topic "/sensor/humidity" represents data from a humidity sensor.
  • Message (Message): the information transmitted in communication. MQTT messages can contain topics and payloads, and the payload can be any binary data.

2. Use MQTT protocol to implement IoT communication

  1. Install MQTT server

First, you need to install the MQTT message proxy server on the server . Commonly used MQTT servers include Mosquitto and EMQX.

On Ubuntu systems, Mosquitto can be installed through the following command:

$ sudo apt-get update
$ sudo apt-get install mosquitto mosquitto-clients
  1. PHP can connect to the MQTT server

PHP can call the MQTT client library, To connect to the MQTT message broker server to implement the functions of publishing and subscribing messages. Commonly used MQTT client libraries include phpMQTT and MQTT.php.

Using the phpMQTT library, you can use the following code to connect to the MQTT server and publish messages:

<?php
require("phpMQTT.php");

$mqtt = new phpMQTT("example.com", 1883, "PHP MQTT Client");

if ($mqtt->connect()) {
    $mqtt->publish("/sensor/humidity", "25");
    $mqtt->close();
} else {
    echo "Connection failed!";
}
?>

In the above code, you need to provide the address and port number of the MQTT server, as well as the client's ID. The connect() method can be used to connect to the MQTT server, the publish() method is used to publish messages, and the close() method can close the MQTT connection.

  1. PHP subscribes to MQTT topics

In addition to publishing messages, PHP can also subscribe to MQTT topics and receive messages sent by the MQTT server.

Using the phpMQTT library, you can implement the functions of subscribing to topics and receiving messages through the following code:

<?php
require("phpMQTT.php");

function messageHandler($topic, $payload) {
    echo "Received message on topic: $topic
Payload: $payload

";
}

$mqtt = new phpMQTT("example.com", 1883, "PHP MQTT Client");

if ($mqtt->connect()) {
    $mqtt->subscribe("/sensor/temperature", "messageHandler");
    while ($mqtt->proc()) {}
    $mqtt->close();
} else {
    echo "Connection failed!";
}
?>

In the above code, use the subscribe() method to subscribe to the /mainstreet/topic topic, $payload parameter It is the message received by the callback function messageHandler(). code>while ($mqtt->proc()) {} loop can maintain the subscription state, receive and process messages from the MQTT server.

3. Use PHP and MQTT protocol to realize IoT control

MQTT protocol can not only be used to realize IoT communication, but also can be used to realize device control. The MQTT server can receive messages from clients and then send the messages to other clients that need to receive messages. In this way, control between devices can be achieved.

  1. Control LED lights

The following is a sample code for controlling LED lights using MQTT protocol and PHP:

<?php
require("phpMQTT.php");

function messageHandler($topic, $payload) {
    $pattern = '/^led=(on|off)$/';
    if (preg_match($pattern, $payload, $matches)) {
        if ($matches[1] == "on") {
            system("gpio write 0 1"); // Turn on LED
        } else {
            system("gpio write 0 0"); // Turn off LED
        }
    }
}

$mqtt = new phpMQTT("example.com", 1883, "PHP MQTT Client");

if ($mqtt->connect()) {
    $mqtt->subscribe("/devices/led", "messageHandler");
    while ($mqtt->proc()) {}
    $mqtt->close();
} else {
    echo "Connection failed!";
}
?>

In the above code, GPIO control is used LED light switch, when the message received by MQTT conforms to the "led=on" or "led=off" format, the LED light switch will be controlled.

  1. Control the motor

The following is a sample code for controlling the motor using the MQTT protocol and PHP:

<?php
require("phpMQTT.php");

function messageHandler($topic, $payload) {
    $pattern = '/^motor=(forward|backward|stop)$/';
    if (preg_match($pattern, $payload, $matches)) {
        if ($matches[1] == "forward") {
            // Turn motor forward
        } elseif ($matches[1] == "backward") {
            // Turn motor backward
        } else {
            // Stop motor
        }
    }
}

$mqtt = new phpMQTT("example.com", 1883, "PHP MQTT Client");

if ($mqtt->connect()) {
    $mqtt->subscribe("/devices/motor", "messageHandler");
    while ($mqtt->proc()) {}
    $mqtt->close();
} else {
    echo "Connection failed!";
}
?>

In the above code, regular expression matching is used If the content of the MQTT message conforms to the "motor=forward", "motor=backward" or "motor=stop" format, it will control the movement direction of the motor.

Summary

This article introduces how to use PHP and MQTT protocols to implement communication and control of the Internet of Things. Through the MQTT protocol, communication and control between devices can be achieved in low-bandwidth and unreliable network environments, which is the basis for IoT applications.

The above is the detailed content of Communication and control of the Internet of Things using PHP and MQTT. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
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.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools