phpMQTT Documentation

repository·master·Indexed 21 days ago

https://github.com/bluerhinos/phpmqtt

A lightweight PHP library providing a simple interface for interacting with MQTT brokers. It supports core operations including connecting, publishing, and subscribing, with specific implementation patterns for both standard web requests and long-running CLI scripts.

Tokens
536
Snippets
4
Records
5
Agent score
23%

What's inside phpMQTT

  1. Run a long-running MQTT subscriber script

    master

    To create a script that stays active and waits for incoming messages on subscribed topics, use a pattern similar to subscribe.php.

    Important: This pattern is intended for command-line execution (CLI) and is not suitable for standard web requests (like PHP-FPM/Apache), as it is designed to run continuously.

    $ php subscribe.php
  2. Publish an MQTT message

    master

    To send a message to a specific topic, use the publish() method.

    Execution Patterns:

    • Web Request: If running as a standard web request, you can simply call $mqtt->connect(), $mqtt->publish(), and $mqtt->close().
    • Long-running CLI Script: If the script is intended to stay alive, you must call $mqtt->proc() regularly to maintain the connection with the broker and handle background processing.
    // For web requests
    $mqtt->connect();
    $mqtt->publish('topic', 'message');
    $mqtt->close();
    
    // For long-running CLI scripts
    $mqtt->connect();
    // ... inside a loop ...
    $mqtt->proc();
    $mqtt->publish('topic', 'message');
  3. Subscribe and wait for a single message

    master

    If you need to display a message on a website by fetching it upon request, use the $mqtt->subscribeAndWaitForMessage() method. This method subscribes to a topic and blocks execution until a message is received, which it then returns.

    Tip: To ensure messages appear instantly when a user loads a page, consider using retained messages on the broker side.

    $message = $mqtt->subscribeAndWaitForMessage('your/topic');