CloudAMQP with PHP Getting started

To access CloudAMQP (or any RabbitMQ/AMQP server) from PHP php-amqplib is a good choice. The library php-amqplib was used for the PHP examples of RabbitMQ in Action and in the official RabbitMQ tutorials.

Code example Publish and Subscribe

The following code snippet show how to connect, publish and consume a message via CloudAMQP.

define('AMQP_DEBUG', false);
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Connection\AMQPSSLConnection;
use PhpAmqpLib\Message\AMQPMessage;
$url = parse_url(getenv('CLOUDAMQP_URL'));
$vhost = substr($url['path'], 1);
if($url['scheme'] === "amqps") {
    $ssl_opts = array(
        'capath' => '/etc/ssl/certs'
    $conn = new AMQPSSLConnection($url['host'], 5671, $url['user'], $url['pass'], $vhost, $ssl_opts);    
} else {
    $conn = new AMQPStreamConnection($url['host'], 5672, $url['user'], $url['pass'], $vhost);    
$ch = $conn->channel();
$exchange = '';
$queue = 'basic_get_queue';
$ch->queue_declare($queue, false, true, false, false);
$ch->exchange_declare($exchange, 'direct', true, true, false);
$ch->queue_bind($queue, $exchange);
$msg_body = 'the body';
$msg = new AMQPMessage($msg_body, array('content_type' => 'text/plain', 'delivery_mode' => 2));
echo "Sending message...\n";
$ch->basic_publish($msg, $exchange);
$retrived_msg = $ch->basic_get($queue);
echo sprintf("Message recieved: %s\n", $retrived_msg->body);

The full code example can be found at

Alternative clients

PECL AMQP library built on top of the RabbitMQ C client
A complete AMQP protocol implementation and a set of libraries for writing AMQP producers and consumers.
Vorpal Bunny
Vorpal Bunny is an experimental rabbitmq-jsonrpc-channel PHP driver designed to allow expedited single call HTTP delivery for Basic.Deliver calls to RabbitMQ.