view raw
Ayush Gupta Ayush Gupta - 6 months ago 71
PHP Question

Keep a MQTT Client Connection always active

I am using

as a
MQTT broker
in my Pub-Sub based application. I am using my
to publish data to the
CloudMQTT server
over a
, and I plan to
to the broker on my webpage to recieve the transmitted information.

I am using this procedure to create a

Code goes as follows:

// subscribe.php

$host = "hostname";
$port = port;
$username = "username";
$password = "password";

$mqtt = new phpMQTT($host, $port, "ClientID".rand());


//currently subscribed topics
$topics['topic'] = array("qos"=>0, "function"=>"procmsg");


function procmsg($topic,$msg){
echo "Msg Recieved: $msg";

Here is the

However, the issue in this case is that it recieves data only when the webpage is open.. I want to keep the connection alive even if the webpage is not open to always recieve published messages, how can I do it?

EDIT : I might be open to using some other technology on the server to handle this subscription process, if anyone can recommend some alternatives

njh njh

PHP's typically mode of operation is to start a process, wait for an HTTP connection, handle the request and then start a new process. This doesn't fit well with the typical MQTT mode of having a long-running process; hence closing the MQTT connection when you close the web page.

It is possible to subscribe to a MQTT topic in a long-running CLI PHP script, but you will have to have some other mechanism to keep the process running. There are a lot of different ways of doing this, depending on your preferences and operating system:

  • a script started using /etc/rc.local at system startup
  • using a init.d script
  • using a process manager, such as DJB's daemontools or runit
  • If you are using Ubuntu, then upstart is a popular mechanism

Searching stackoverflow finds the following related question and several answers: