Getting started: Pub/Sub in PHP
This guide will get you started with Ably Pub/Sub in PHP.
It will take you through the following steps:
- Create a client and establish a connection to Ably with the Rest SDK.
- Generate a JWT for authenticating frontend clients.
- Publish a message to the channel with your client for subscribers to receive.
- Retrieve the presence set of the channel.
- Retrieve the messages you sent in the guide from history.
Prerequisites
- Sign up for an Ably account.
- Create a new app, and create your first API key.
- Your API key will need the
publish
,presence
, andhistory
capabilities.
- Install the Ably CLI:
npm install -g @ably/cli
CopyCopied!
- Run the following to log in to your Ably account and set the default app and API key:
ably login
ably apps switch
ably auth keys switch
CopyCopied!
- Install PHP version 7.2 or greater.
- Create a new project and install the Ably Pub/Sub PHP SDK:
# Create a new directory for your project
mkdir ably-php-quickstart
cd ably-php-quickstart
# Initialize Composer (if you don't have a composer.json yet)
composer init
# Install the Ably PHP SDK
composer require ably/ably-php
CopyCopied!
Clients can make REST API requests to Ably when they instantiate a REST SDK instance. This enables them to publish messages to channels and retrieve channel information.
- Create a
get_started.php
file in your project and add the following code to instantiate the SDK and make requests to Ably. At the minimum you need to provide an authentication mechanism. Using an API key directly is fine for server-side environments like PHP where the key remains secure. However, for frontend clients, you should use token authentication instead of exposing API keys. In this example, theclientId
will be the name of the client sending the message:
<?php
require 'vendor/autoload.php';
use Ably\AblyRest;
$ably = new AblyRest(['key' => '<loading API key, please wait>', 'clientId' => 'my-first-client']);
Demo OnlyCopyCopied!
Step 2: Generate a JWT
The Ably PHP SDK provides token authentication for secure client connections. Authentication with a JWT is recommended over using API keys directly in production because they can be scoped to specific capabilities and have expiration times. This is essential when authenticating frontend clients where embedding API keys would expose them publicly. With PHP the API key would be considered secure as it’s stored on the server.
This section will show you how to build a JWT with the Ably API key credentials embedded, which you can then return to your frontend clients, for example from an API endpoint.
First install the Firebase JWT library, which is used to create and verify JSON Web Tokens (JWTs):
composer require firebase/php-jwt
CopyCopied!
Import the necessary classes at the top of your get_started.php
file:
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
CopyCopied!
Then create a new JWT with the following code:
$currentTime = time();
$payload = [
'iat' => $currentTime,
'exp' => $currentTime + 3600,
'x-ably-capability' => '{"*":["*"]}'
];
$apiKeyCredentials = explode(':', '<loading API key, please wait>');
$jwt = JWT::encode(
$payload,
$apiKeyCredentials[1],
'HS256',
$apiKeyCredentials[0]
);
echo $jwt;
Demo OnlyCopyCopied!
To use this JWT for authenticating frontend clients, you would typically expose it through an API endpoint that your frontend application can call. For example, you might create an endpoint like /get-auth-jwt
that returns this JWT. Your frontend clients, a JavaScript application in the example below, can then use this JWT when instantiating their Ably client:
const realtime = new Ably.Realtime({ authUrl: '/get-auth-jwt' });
CopyCopied!
This approach keeps your API key secure on the server while allowing frontend clients to authenticate with Ably using the generated JWT.
Messages contain the data that a client is communicating, such as a short ‘hello’ from a colleague, or a financial update being broadcast to subscribers from a server. Ably uses channels to separate messages into different topics, so that clients only ever receive messages on the channels they are subscribed to. The PHP SDK can only publish messages to channels and cannot subscribe to them. To subscribe to channels you will make use of the Ably CLI.
- Use the Ably CLI to subscribe to a channel. The message that your PHP client sends will be received by CLI instance.
ably channels subscribe my-first-channel
CopyCopied!
- Add the following lines to the bottom of your
get_started
file to create a channel instance and publish a message to the channel. Then run it withphp get_started.php
:
$channel = $ably->channel('my-first-channel');
$channel->publish('myEvent', 'Hello!');
CopyCopied!
The Ably CLI will receive the message.
Step 4: Presence
Presence enables clients to be aware of one another if they are present on the same channel. You can then show clients who else is online, provide a custom status update for each, and notify the channel when someone goes offline. With the PHP SDK you can retrieve the presence set but cannot enter it. This means you can see who is present on a channel, but you cannot announce your own presence from a PHP client.
- Have a client join the presence set using the Ably CLI:
ably channels presence enter my-first-channel --client-id "my-cli" --data '{"status":"learning about Ably!"}'
CopyCopied!
- Add the following lines to your
get_started
function to retrieve the list of members in the presence set. Then run it withphp get_started.php
:
$membersPage = $channel->presence->get(); // Returns a PaginatedResult
$memberIds = array_map(function($member) {
return $member->clientId;
}, $membersPage->items);
echo "\nMembers in presence set:\n " . implode(', ', $memberIds) . "\n";
CopyCopied!
You can retrieve previously sent messages using the history feature. Ably stores all messages for 2 minutes by default in the event a client experiences network connectivity issues. This can be extended for longer if required.
If more than 2 minutes has passed since you published a regular message (excluding the presence events), then you can publish some more before trying out history. You can use the Pub/Sub SDK, Ably CLI or the dev console to do this.
For example, using the Ably CLI to publish 5 messages:
ably channels publish --count 5 my-first-channel "Message number {{.Count}}" --name "myEvent"
CopyCopied!
- Add the following lines to your
get_started
function to retrieve any messages that were recently published to the channel. Then run it withphp get_started.php
:
$history = $channel->history();
echo "\nMessage History:\n";
echo str_repeat("-", 50) . "\n";
foreach ($history->items as $index => $message) {
echo " * " . ($message->data ?? 'null') . "\n";
}
CopyCopied!
The output will look similar to the following:
[
'Message number 5',
'Message number 4',
'Message number 3',
'Message number 2',
'Message number 1'
]
CopyCopied!
Next steps
Continue to explore the documentation with PHP as the selected language:
Read more about the concepts covered in this guide:
- Revisit the basics of Pub/Sub
- Explore more advanced Pub/Sub concepts
- Read more about how to use presence in your apps
- Fetch message history in your apps
You can also explore the Ably CLI further, or visit the Pub/Sub API references.