Note: php5-dev can be replace by new version as php7.2-dev
1. sudo apt-get install php-pear
2. sudo apt-get install php5-dev
3. sudo apt-get install libmosquitto-dev
4. sudo pecl install Mosquitto-alpha
If step 4 display Please provide the prefix of the libmosquitto installation [autodetect] :
we can enter any character
5. cd /etc/php5/mods-available
6. sudo vi mosquitto.ini
Step 6 will oppen vi (or vim, nano,...) editer, add following line
extension=mosquitto.so
Save the file and quit the editor. (ESC -> :wq)
7 Check if the library is installed using dpkg
dpkg -l | grep mosquitto
You will get a result similar to the one given below. You must see mosquitto library listed.
root@piserver:/etc/php5/mods-available# dpkg -l | grep mosquitto
ii libmosquitto-dev 1.3.4-2+deb8u1 all MQTT version 3.1 client library, development files
ii libmosquitto1 1.3.4-2+deb8u1 armhf MQTT version 3.1 client library
ii mosquitto 1.3.4-2+deb8u1 armhf MQTT version 3.1/3.1.1 compatible message broker
ii mosquitto-clients 1.3.4-2+deb8u1 armhf Mosquitto command line MQTT clients
ii python-mosquitto 1.3.4-2+deb8u1 all MQTT version 3.1 Python client library
8/ Now enable the mosquitto module php5enmod can be replace by phpenmod
sudo php5enmod mosquitto
9/ Restart apache server if need or restart server
sudo service apache2 restart
1/ Creating an MQTT subscriber ( sub.php ) using Mosquitto-PHP library
<?php
$client = new Mosquitto\Client();
// set user and pass for mqtt if need
$client->setCredentials("userhere", "passhere");
$client->onConnect('connect');
$client->onDisconnect('disconnect');
$client->onSubscribe('subscribe');
$client->onMessage('message');
$client->connect("localhost", 1883, 60);
$client->subscribe('#', 1);
while (true) {
$client->loop();
sleep(2);
}
$client->disconnect();
unset($client);
function connect($r) {
echo "I got code {$r}\n";
}
function subscribe() {
echo "Subscribed to a topic\n";
}
function message($message) {
printf("\nGot a message on topic %s with payload:%s",
$message->topic, $message->payload);
}
function disconnect() {
echo "Disconnected cleanly\n";
}
2/ Run in backgroud
php sub.php queue:listen --tries=3 >/dev/null 2>&1 &
Link:
[1] http://www.notespoint.com/mosquitto-php-library-install/
[2] https://www.wingsquare.com/blog/developing-php-client-for-mqtt-using-mosquitto-php-library/