phpMQTT Documentation
repository·master·Indexed 21 days ago
https://github.com/bluerhinos/phpmqttA 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.
What's inside phpMQTT
- phpMQTT is a simple PHP class designed to allow PHP applications to connect to, publish to, and subscribe to an MQTT broker.
Install phpMQTT via Composer
masterTo add phpMQTT to your project, use Composer to require the package. Note that the current version is specified using the
@devflag.composer require bluerhinos/phpmqtt=@devRun a long-running MQTT subscriber script
masterTo 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.phpPublish an MQTT message
masterTo 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');- Web Request: If running as a standard web request, you can simply call
Subscribe and wait for a single message
masterIf 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');