PubNub PHP SDK 5.1.0

This page outlines the steps to follow to create a simple Hello, World application with PubNub. This covers the basics of integrating PubNub in your application: setting up a connection to PubNub, and sending and receiving messages.

  1. PubNub account
  2. Download the SDK
  3. Send messages

PubNub account

Sign in or create an account to create an app on the Admin Portal and get the keys to use in your application.

When you create a new app, the first set of keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.

Download the SDK

Download the SDK from any of the following sources:

Without composer

  1. Clone the following repository: git clone https://github.com/pubnub/php.git ./pubnub-php

  2. Copy the src folder to your project.

  3. Include autoloader.php file in your project:

    require_once('src/autoloader.php');
  4. Download dependency monolog from https://github.com/Seldaek/monolog and copy the monolog folder from the src folder to the src folder of your project.

  5. Download dependency psr/Log from https://github.com/php-fig/log/tree/master and copy the psr folder to the src folder of your project.

  6. Download dependency rmccue from https://github.com/WordPress/Requests and copy the Requests folder and the file Requests.php from the library folder to the src folder of your project.

With composer

  1. Add the PubNub package to your composer.json file:

    {
    "require": {
    "pubnub/pubnub": "5.1.0"
    }
    }
  2. Run composer install --no-dev‌ from the command line. This installs the PubNub PHP SDK and all its dependencies in the vendor folder of the project.

  3. Include autoload.php file in your project:

    require_once('vendor/autoload.php');

Get the source code

Configure PubNub

In this guide, you will be working with two files:

  • subscribe.php which will subscribe and print out every message sent to the channel
  • publish.php which will send a message to the channel every time you run the file

In the IDE of your choice, create two empty files: subscribe.php and publish.php. In the subscribe.php, add the following content. This is the minimum configuration you need to send and receive messages with PubNub. Do not worry about import statements for now.

Make sure to replace myPublishKey and mySubscribeKey with your app's publish and subscribe keys from the Admin Portal.

$pnconf = new PNConfiguration();
$pubnub = new PubNub($pnconf);

$pnconf->setSubscribeKey("mySubscribeKey");
$pnconf->setPublishKey("myPublishKey");
$pnconf->setUserId("gettingStartedSubscriber");

For more information, refer to the Configuration section of the SDK documentation.

Add event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

Copy the following code to configure your subscribe.php file such that when it receives a message, it prints out the message's content and publisher.

class MySubscribeCallback extends SubscribeCallback {
function status($pubnub, $status) {
if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
// This event happens when radio / connectivity is lost
} else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
// Connect event. You can do stuff like publish, and know you'll get it
// Or just use the connected event to confirm you are subscribed for
// UI / internal notifications, etc
} else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
// Handle message decryption error. Probably client configured to
// encrypt messages and on live data feed it received plain text.
}
}

function message($pubnub, $message) {
show all 27 lines

For more information, refer to the Listeners section of the SDK documentation.

Publish and subscribe

To receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone subscribed to that channel.

In this app, publishing a message is triggered by running the publish.php file you created previously. The publish() method uses the channel and message parameters that you can see in the following code. Copy the code and paste it into your publish.php file. Do not worry about import statements and PubNub configuration in this file for now.

$result = $pubnub->publish()
->channel("hello_world")
->message("Hello PubNub from PHP")
->sync();

To subscribe, you send a subscribe() call. Copy the following code and paste it into your subscribe.php file:

$pubnub->subscribe()
->channels("hello_world")
->execute();

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Putting it all together

Composer

The following code uses Composer to download PubNub.

Your files should now look similar to the ones below:

subscribe.php

<?php

require_once('vendor/autoload.php');

use PubNub\PubNub;
use PubNub\Enums\PNStatusCategory;
use PubNub\Callbacks\SubscribeCallback;
use PubNub\PNConfiguration;

$pnconf = new PNConfiguration();
$pubnub = new PubNub($pnconf);

$pnconf->setSubscribeKey("mySubscribeKey");
$pnconf->setPublishKey("myPublishKey");
$pnconf->setUserId("gettingStartedSubscriber");
show all 48 lines

publish.php

<?php

require_once('vendor/autoload.php');

use PubNub\PubNub;
use PubNub\PNConfiguration;

$pnconf = new PNConfiguration();
$pubnub = new PubNub($pnconf);

$pnconf->setSubscribeKey("mySubscribeKey");
$pnconf->setPublishKey("myPublishKey");
$pnconf->setUserId("gettingStartedPublisher");

// Use the publish command separately from the Subscribe code shown above.
show all 22 lines

Save both files and open them using the terminal. You can use the one that is built in your IDE or the one that your operating system provides. Make sure to run the subscribe.php file before you run the publish.php file. Otherwise you will send the message without subscribing to the channel first and will not see your message displayed in the terminal.

You should see output similar to the following in the terminal window in which you ran the subscribe.php file:

Hello PubNub
gettingStartedPublisher

Congratulations! You've just subscribed to a channel and sent your first message.

Walkthrough

Instead of focusing on the order in which you wrote the code, let's focus on the order in which it runs. The app you just created does a few things:

  • configures a PubNub connection
  • adds the message event listener
  • subscribes to a channel
  • publishes a message

Configuring PubNub

The following code is the minimum configuration you need to send and receive messages with PubNub. For more information, refer to the Configuration section of the SDK documentation.

$pnconf = new PNConfiguration();
$pubnub = new PubNub($pnconf);

$pnconf->setSubscribeKey("mySubscribeKey");
$pnconf->setPublishKey("myPublishKey");
$pnconf->setUserId("gettingStartedSubscriber");

Note that you had to configure PubNub for both files and the only difference in configuration was the UserId.

Adding event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

You added two listeners to the app: status and message. Status listens for status events but in your app it is a no-op implementation. The other listener, message, listens for incoming messages on a particular channel. When it receives a message, the app simply prints the received message and the value of the publishing client's UserId parameter. This is why you see "Hello World" and "gettingStartedPublisher" displayed in the console.

class MySubscribeCallback extends SubscribeCallback {
function status($pubnub, $status) {
if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
// This event happens when radio / connectivity is lost
} else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
// Connect event. You can do stuff like publish, and know you'll get it
// Or just use the connected event to confirm you are subscribed for
// UI / internal notifications, etc
} else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
// Handle message decryption error. Probably client configured to
// encrypt messages and on live data feed it received plain text.
}
}

function message($pubnub, $message) {
show all 27 lines

For more information, refer to the Listeners section of the SDK documentation.

Publishing and subscribing

PubNub uses the Publish/Subscribe model for real-time communication. This model involves two essential parts:

  • Channels are transient paths over which your data is transmitted
  • Messages contain the data you want to transmit to one or more recipients

When you want to receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel. In this example, you subscribe to a channel named hello_world.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB. PubNub will, in most cases, deliver your message to its intended recipients in fewer than 100 ms regardless of their location. You can also share files up to 5MB.

When you open the publish.php file, the publish() method is called which effectively sends the "Hello World" message.

$result = $pubnub->publish()
->channel("hello_world")
->message("Hello PubNub")
->sync();

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Next steps

You have just learned how to use the PHP SDK to send and receive messages using PubNub. Next, take a look at the SDK's reference documentation which covers PubNub API in more detail.