CloudAMQP with MQTT and PHP Getting started

A simple php class that can be used to connect, publish and subscribe from CloudAMQP MQTT is phpMQTT.

The ClientId is the unique MQTT client id to use for the device.

Code example Publish

require("phpMQTT.php");

$host = "hostname";
$port = port;
$username = "username";
$password = "password";
$message = "Hello CloudAMQP MQTT!";

//MQTT client id to use for the device. "" will generate a client id automatically
$mqtt = new phpMQTT($host, $port, "ClientID".rand());

if ($mqtt->connect(true,NULL,$username,$password)) {
  $mqtt->publish("topic",$message, 0);
  $mqtt->close();
}else{
  echo "Fail or time out
"; }

Code example Subscribe

require("phpMQTT.php");

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

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

if(!$mqtt->connect(true,NULL,$username,$password)){
  exit(1);
}

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

while($mqtt->proc()){
}

$mqtt->close();
function procmsg($topic,$msg){
  echo "Msg Recieved: $msg";
}

Mosquitto-PHP

Another option is to use Mosquitto-PHP. Good examples can be found here.