Getting Started with RabbitMQ in PHP

In this tutorial I’ll walk you through using message broker software RabbitMQ with PHP. It acts as a middleman between a producer and a consumer. A producer being the data that we want to pass, and consumer being the entity that we want to pass it to. RabbitMQ uses a queue, which you can think of as a mailbox where you drop your letters. RabbitMQ then takes the letters and delivers them to their destination.

Installing RabbitMQ

In Ubuntu and other Debian-based operating systems you can install RabbitMQ by executing the following commands from your terminal:

  1. echo "deb testing main"  | sudo tee  /etc/apt/sources.list.d/rabbitmq.list > /dev/null
  2. sudo wget
  3. sudo apt-key add rabbitmq-signing-key-public.asc
  4. sudo apt-get update
  5. sudo apt-get install rabbitmq-server -y
  6. sudo service rabbitmq-server start
  7. sudo rabbitmq-plugins enable rabbitmq_management
  8. sudo service rabbitmq-server restart

The first command appends the RabbitMQ source to the software sources list. Next, we download the RabbitMQ signing key using wget and add it to Ubuntu. Then we call apt-get update to update the software sources list. Afterwards, we install the RabbitMQ server, start it and enable its management plugin. This provides an HTTP-based API management for monitoring your RabbitMQ server. Finally, we restart the RabbitMQ server so that changes will take effect.

The default username and password is guest. And the default port in which it runs is 5672.

If you’re on another operating system, you can find how to install RabbitMQ for your specific operating system here: Downloading and Installing RabbitMQ.

Working with RabbitMQ

Once you’re done installing RabbitMQ, we can now install the AMQP library for PHP, which implements the Advanced Messaging Queue Protocol. Start by creating a new directory, which is where we’ll put all the files for testing RabbitMQ. Next, create a composer.json file and add the following:

  1. {
  2.   "require": {
  3.       "videlalvaro/php-amqplib": "2.2.*"
  4.   }
  5. }

Open up your terminal and cd into the directory you created earlier, then execute composer install to install the AMQP library.

Before we move on, lets also install Swiftmailer. You can do that by executing the following command from your terminal. This also adds an entry to Swiftmailer to your composer.json:

  1. composer require swiftmailer/swiftmailer @stable

If you haven’t figured it out by now, we’ll be using Swiftmailer for the sample app we’re creating, which will send emails to our imaginary users. Normally, emails takes a few seconds before they’re sent. Adding an attachment to an email also adds to that time. In the real world we don’t really want our users to wait. What we want to do is make them believe that we’ve already sent the email by showing a message that it’s been sent.

This is where RabbitMQ comes in. We’ll use it as some sort of a mailbox that multiple users can just drop their messages in. RabbitMQ will then take care of sending the messages in the background.

Sending Messages

First let’s create the form to be used for sending emails. It’ll accept the name and email address of the sender, the email address of the receiver and then the subject and message. Name the file form.php:

  1. <?php
  2. if(!empty($_GET['sent'])){
  3. ?>
  4. <div>
  5.     Your message was sent!
  6. </div>
  7. <?php
  8. }
  9. ?>
  10. <form action="mailer.php" method="POST">
  11.     <div>
  12.         <label for="from">From</label>
  13.         <input type="text" name="from" id="from">      
  14.     </div>
  15.     <div>
  16.         <label for="from_email">From Email</label>
  17.         <input type="text" name="from_email" id="from_email">      
  18.     </div>
  19.     <div>
  20.         <label for="to_email">To Email</label>
  21.         <input type="text" name="to_email" id="to_email">          
  22.     </div>
  23.     <div>
  24.         <label for="subject">Subject</label>
  25.         <input type="text" name="subject" id="subject">
  26.     </div>
  27.     <div>
  28.         <label for="message">Message</label>
  29.         <textarea name="message" id="message" cols="30" rows="10"></textarea>  
  30.     </div>
  31.     <div>
  32.         <button type="submit">Send</button>
  33.     </div>
  34. </form>

Next, create the file that will push the message into the queue, and name it file sender.php.

Require the autoload.php file so that our dependencies will be automatically loaded by PHP. Then use the AMQPConnection and AMQPMessage from the AMQP library. AMQPConnection allows us to create a new connection to the RabbitMQ server and AMQPMessage allows us to create messages that we can push to the queue.

  1. <?php
  2. require_once __DIR__ . '/vendor/autoload.php';
  3. use PhpAmqpLib\Connection\AMQPConnection;
  4. use PhpAmqpLib\Message\AMQPMessage;
  6. $connection = new AMQPConnection('localhost', 5672, 'guest', 'guest');
  7. $channel = $connection->channel();
  9. $channel->queue_declare('email_queue', false, false, false, false);
  11. $data = json_encode($_POST);
  13. $msg = new AMQPMessage($data, array('delivery_mode' => 2));
  14. $channel->basic_publish($msg, '', 'email_queue');
  16. header('Location: form.php?sent=true');

Breaking it down, first we create a fresh connection by creating a new instance of the AMQPConnection class. This requires the following arguments:

  • host – The host that the RabbitMQ server is running on. In this case we’ve installed RabbitMQ on the same computer we’re running the script in. So it should be localhost. Note that in the real world we’ll install RabbitMQ on another server, different from the one were using to serve our websites. So instead of localhost we’d use the public IP address of that server.
  • port – The port that the RabbitMQ server is running on.
  • user – The username for logging into the server. By default, the username is set to guest.
  • password – The password for logging into the server. By default, the password is set to guest.

Now, we’ll create a channel. We can do that by calling the channel() method from the connection that we’ve just declared.

  1. $channel = $connection->channel();

Then we’ll declare the queue to be used by calling the queue_declare method.

  1. $channel->queue_declare('email_queue', false, false, false, false);

The queue_declare method takes up the following arguments:

  • queue name – A name that you want to use for the queue. You can supply anything for this.
  • passive – A boolean value for specifying whether to check for an existing exchange.
  • durable – A boolean value for specifying whether the RabbitMQ holds on to a queue when the server crashes.
  • exclusive – A boolean value for specifying whether the queue is used by only one connection.
  • auto-delete – A boolean value for specifying whether the queue is deleted when the last subscriber unsubscribes.

Next we convert the POST data that we receive from the form to a JSON string. We can only pass strings as a message so we’ll have to convert this later on into an array on the receiver’s end.

  1. $data = json_encode($_POST);

Next we create a new message. This accepts 2 arguments: the data and an array of options. For the array of options we specify the delivery_mode to 2 which means that the message is persistent. This means that it isn’t lost when the server crashes or an error occurs.

  1. $msg = new AMQPMessage($data, array('delivery_mode' => 2));

Next we’ll publish the message by calling the basic_publish() method on the channel. This accepts 3 arguments: the message, the exchange and the name of the queue. If you’re wondering why we set the value of exchange to an empty string, that’s because we don’t really need it. The exchange is commonly used for pub-sub patterns. What were using here is just basic publish.

  1. $channel->basic_publish($msg, '', 'email_queue');

Finally, we just redirect the user to the form.

  1. header('Location: form.php?sent=true');

Receiving Messages

Now we’re ready to write the code that will receive the messages sent by users. Name the file receiver.php. Here’re the full contents of the file:

  1. <?php
  2. require_once __DIR__ . '/vendor/autoload.php';
  3. use PhpAmqpLib\Connection\AMQPConnection;
  5. $connection = new AMQPConnection('localhost', 5672, 'guest', 'guest');
  6. $channel = $connection->channel();
  8. $channel->queue_declare('email_queue', false, false, false, false);
  10. echo ' * Waiting for messages. To exit press CTRL+C', "\n";
  12. $callback = function($msg){
  14.     echo " * Message received", "\n";
  15.     $data = json_decode($msg->body, true);
  17.     $from = $data['from'];
  18.     $from_email = $data['from_email'];
  19.     $to_email = $data['to_email'];
  20.     $subject = $data['subject'];
  21.     $message = $data['message'];
  23.     $transporter = Swift_SmtpTransport::newInstance('', 465, 'ssl')
  24.       ->setUsername('YOUR_GMAIL_EMAIL')
  25.       ->setPassword('YOUR_GMAIL_PASSWORD');
  27.     $mailer = Swift_Mailer::newInstance($transporter);  
  29.     $message = Swift_Message::newInstance($transporter)
  30.         ->setSubject($subject)
  31.         ->setFrom(array($from_email => $from))
  32.         ->setTo(array($to_email))
  33.         ->setBody($message);
  35.     $mailer->send($message);
  37.     echo " * Message was sent", "\n";
  38.     $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
  39. };
  41. $channel->basic_qos(null, 1, null);
  42. $channel->basic_consume('email_queue', '', false, false, false, false, $callback);
  44. while(count($channel->callbacks)) {
  45.     $channel->wait();
  46. }

Breaking it down, the first 5 lines of code are basically the same as the one we have on the sender.php file. Then we just output a message saying how we can stop the file from running. We need to run this file from the terminal, so to stop it we just hit CTRL + C.

Now we’ll declare a named function used for processing the message that we passed from the sender. The first thing it does is output that the message was received. Then we use json_decode() to convert the JSON string back to an array.

  1. $callback = function($msg){
  2.     echo " * Message received", "\n";
  3.     $data = json_decode($msg->body, true);
  4. };

Next we’ll extract the data and assign them to each of their own variables:

  1. $from = $data['from'];
  2. $from_email = $data['from_email'];
  3. $to_email = $data['to_email'];
  4. $subject = $data['subject'];
  5. $message = $data['message'];

Then we declare a new transporter to be used by Swiftmailer, which allows us to use a gmail account for sending emails. Declaring a new instance accepts 3 arguments: the host, port and the encryption. Then we set the username and password.

  1. $transporter = Swift_SmtpTransport::newInstance('', 465, 'ssl')
  2.       ->setUsername('YOUR_GMAIL_EMAIL')
  3.       ->setPassword('YOUR_GMAIL_PASSWORD');

Our next order of business is declaring a new mailer instance, and supplying the transporter as an argument.

  1. $mailer = Swift_Mailer::newInstance($transporter);  

Then we’ll create a new message, which also takes up the transporter as its argument. We then set the subject, from field, to field, and body of the message.

  1. $message = Swift_Message::newInstance($transporter)
  2.         ->setSubject($subject)
  3.         ->setFrom(array($from_email => $from))
  4.         ->setTo(array($to_email))
  5.         ->setBody($message);

Finally, we send the message and output that the message was sent. The last line basically tells RabbitMQ that the sending of the message has indeed been successful.

  1. $mailer->send($message);
  2. echo " * Message was sent", "\n";
  4. $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);

Running the program

You can now run the receiver by going to your terminal and executing the following command:

  1. php receiver.php

Once it’s running, go to your browser and access the sender.php file. Enter the details of your message and click on send. You’re instantly greeted by a ‘Your message was sent!’ text, but if you immediately check your email account its not there yet. If it’s not there then the queue is still processing it. Check the output displayed on the terminal window where you executed the receiver. You should see a ‘Message was sent’ output if the email was already sent.


RabbitMQ is a nice way for implementing messaging applications such as the one we created in this tutorial. We’ve barely scratch the surface of what’s possible with RabbitMQ with this tutorial. I recommend that you check out the getting started guides and the documentation if you’d like to dive deeper.

Author: Wern Ancheta

Scroll to Top