# PHP MQTT with RabbitMQ and LavinMQ

We recommend [php-mqtt/client](https://github.com/php-mqtt/client), a maintained MQTT client for PHP.

```bash
composer require php-mqtt/client
```

## Publish and subscribe

Set `MQTT_HOST`, `MQTT_PORT`, `MQTT_USERNAME` and `MQTT_PASSWORD` to the MQTT details on your instance’s details page in the CloudAMQP console. Port 8883 uses TLS. Without them, the examples connect to a local broker.

Save the publisher as `publisher.php`:

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\MqttClient;

$port = (int) (getenv('MQTT_PORT') ?: 1883);
$client = new MqttClient(getenv('MQTT_HOST') ?: 'localhost', $port, null, MqttClient::MQTT_3_1_1);
$client->connect((new ConnectionSettings())
    ->setUsername(getenv('MQTT_USERNAME') ?: 'guest')
    ->setPassword(getenv('MQTT_PASSWORD') ?: 'guest')
    ->setUseTls($port === 8883));

// QoS 1, and the loop runs until the broker has sent its PUBACK
$client->publish('hello', 'Hello world!', MqttClient::QOS_AT_LEAST_ONCE);
$client->loop(true, true);
echo " [x] Sent 'Hello world!'\n";
$client->disconnect();
```

Save the subscriber as `worker.php`:

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\MqttClient;

$port = (int) (getenv('MQTT_PORT') ?: 1883);
$client = new MqttClient(getenv('MQTT_HOST') ?: 'localhost', $port, null, MqttClient::MQTT_3_1_1);
$client->connect((new ConnectionSettings())
    ->setUsername(getenv('MQTT_USERNAME') ?: 'guest')
    ->setPassword(getenv('MQTT_PASSWORD') ?: 'guest')
    ->setUseTls($port === 8883));

// php-mqtt/client acks each QoS 1 message before calling the handler
$client->subscribe('hello', function (string $topic, string $message) {
    echo " [x] Received '$message'\n";
}, MqttClient::QOS_AT_LEAST_ONCE);
echo " [*] Waiting for messages. To exit press CTRL+C\n";
$client->loop();
```

Run `php worker.php` in one terminal and `php publisher.php` in another.

A runnable example is in [php/php-mqtt-client in cloudamqp/examples](https://github.com/cloudamqp/examples/tree/main/php/php-mqtt-client).

## Good to know

- **Put the vhost in the username**, as `vhost:user`. MQTT has no vhost of its own, and the console shows the username that way.
- **`setUseTls(true)` verifies the server certificate** and hostname.
- **Run the loop.** `loop()` sends and receives messages: the publisher runs it until the broker has sent its PUBACK, and the worker runs it for good.
- **Messages are acked before the handler runs**, so a message is lost if the handler fails. php-mqtt/client acks each QoS 1 message as it arrives.
- **Reconnecting is off by default.** Turn it on with `setReconnectAutomatically(true)` on the `ConnectionSettings`.
