---
source_url: https://www.pubnub.com/docs/sdks/php
title: PHP API & SDK Docs 9.0.0
updated_at: 2026-05-19T12:13:06.934Z
sdk_name: PubNub PHP SDK
sdk_version: 9.0.0
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# PHP API & SDK Docs 9.0.0

PubNub PHP SDK, use the latest version: 9.0.0

Install:

```bash
composer require pubnub/pubnub@9.0.0
```

This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:

* Setting up a connection
* Sending messages
* Receiving messages in real-time

## Overview

This guide will help you get up and running with PubNub in your PHP application. We'll create a simple application that demonstrates how to connect to PubNub, subscribe to channels, and publish messages.

The code examples will work in both web environments and command-line scripts, with notes indicating any environment-specific considerations when relevant.

## Prerequisites

Before we dive in, make sure you have:

* A basic understanding of PHP (v7.0 or newer recommended)
* PHP installed on your system (either on a web server or as CLI)
* Composer (recommended) or the ability to manually manage dependencies
* A PubNub account (we'll help you set this up!)

## Setup

### Get your PubNub keys

First, get your PubNub keys:

* [Sign in](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) on the PubNub Admin Portal.
* Create an app (or use an existing one).
* Find your publish and subscribe keys in the app dashboard.

When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve security and management.

### Install the SDK

:::note SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
:::

Install the PHP SDK using Composer.

1. For a fresh project (no existing code), run the following command in the project directory. 1composer init
2. Then, run this command (for both the existing Composer projects and the newly initiated ones). 1composer require pubnub/pubnub‌

## Steps

### Initialize PubNub

Create a PHP file to initialize the PubNub client:

```php
// Create a new configuration instance
$pnConfiguration = new PNConfiguration();

// Set subscribe key (required)
$pnConfiguration->setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); // Replace with your subscribe key

// Set publish key (only required if publishing)
$pnConfiguration->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); // Replace with your publish key

// Set UUID (required to connect)
$pnConfiguration->setUserId("php-sdk-user-" . uniqid());

// Set up cryptography for message encryption (optional)
// $pnConfiguration->setCryptoModule(CryptoModule::aesCbcCryptor("your-cipher-key", true));

// Configure connection timeout in seconds
$pnConfiguration->setConnectTimeout(10);

// Create PubNub instance with the configured settings
$pubnub = new PubNub($pnConfiguration);
```

For more information, refer to the [Configuration](https://www.pubnub.com/docs/sdks/php/api-reference/configuration) section of the SDK documentation.

### Set up 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.

There are two main types of listeners you'll need to set up:

* Status listener - for connection state changes and operational events
* Event listener - for messages and presence events

Set up listeners to handle events and messages:

```php
class MySubscribeCallback extends SubscribeCallback
{
    public function status($pubnub, $status)
    {
        if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
            // This event happens when radio / connectivity is lost
            echo "Unexpected disconnect - network may be down" . PHP_EOL;
        } elseif ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
            // Connect event. You can do stuff like publish, and know you'll get it
            echo "Connected to PubNub!" . PHP_EOL;
        } elseif ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
            // Handle message decryption error
            echo "Decryption error: " . $status->getException() . PHP_EOL;
        }
    }

    public function message($pubnub, $message)
    {
        // Handle new message stored in message.message
        echo "Received message: " . json_encode($message->getMessage()) . PHP_EOL;
        echo "Publisher: " . $message->getPublisher() . PHP_EOL;
        echo "Channel: " . $message->getChannel() . PHP_EOL;
        echo "Timetoken: " . $message->getTimetoken() . PHP_EOL;
    }

    public function presence($pubnub, $presence)
    {
        // Handle incoming presence data
        echo "Presence event: " . $presence->getEvent() . PHP_EOL;
        echo "UUID: " . $presence->getUuid() . PHP_EOL;
        echo "Channel: " . $presence->getChannel() . PHP_EOL;
        echo "Occupancy: " . $presence->getOccupancy() . PHP_EOL;
    }
}

// Add listener
$subscribeCallback = new MySubscribeCallback();
$pubnub->addListener($subscribeCallback);
```

For more information, refer to the [Listeners](https://www.pubnub.com/docs/sdks/php/api-reference/configuration#event-listeners) section of the SDK documentation.

### Create a subscription

To receive messages, you need to subscribe to a channel:

```php
// Subscribe to a channel
$pubnub->subscribe()
    ->channels("hello_world")
    ->withPresence(true)  // Optional: subscribe to presence events
    ->execute();
```

This operation will block execution since the subscription is a long-running operation.

For web applications, you might want to:

* Run subscriptions in a separate process that logs to a database.
* Use AJAX or server-sent events to push updates to the client.
* Consider using the PubNub JavaScript SDK for client-side real-time updates.

For more information, refer to the [Subscribe](https://www.pubnub.com/docs/sdks/php/api-reference/publish-and-subscribe#subscribe) section of the SDK documentation.

### Publish messages

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.

A message can be any type of JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

To send messages, use the `publish()` method:

```php
// Assuming $pubnub is already initialized

try {
    // Create message data
    $messageData = [
        "text" => "Hello from PHP SDK!",
        "timestamp" => time(),
        "sender" => [
            "name" => "PHP Publisher",
            "id" => $pnConfiguration->getUserId()
        ]
    ];

    // Publish a message to a channel
    $result = $pubnub->publish()
        ->channel("hello_world")              // Channel to publish to
        ->message($messageData)               // Message content
        ->shouldStore(true)                   // Store in history
        ->sync();                             // Execute synchronously

    // Display success message
    echo "Message published successfully!" . PHP_EOL;
    echo "Timetoken: " . $result->getTimetoken() . PHP_EOL;

    // Convert timetoken to readable date
    $timestamp = floor($result->getTimetoken() / 10000000);
    $readableDate = date('Y-m-d H:i:s', $timestamp);
    echo "Published at: " . $readableDate . PHP_EOL;

    // Display published message
    echo PHP_EOL . "Published message: " . PHP_EOL;
    echo json_encode($messageData, JSON_PRETTY_PRINT) . PHP_EOL;
} catch (PubNubServerException $exception) {
    // Handle PubNub server-specific errors
    echo "Error publishing message: " . $exception->getMessage() . PHP_EOL;

    if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) {
        echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL;
    }

    if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) {
        echo "Status Code: " . $exception->getStatusCode() . PHP_EOL;
    }
} catch (PubNubException $exception) {
    // Handle PubNub-specific errors
    echo "PubNub Error: " . $exception->getMessage() . PHP_EOL;
} catch (Exception $exception) {
    // Handle general exceptions
    echo "Error: " . $exception->getMessage() . PHP_EOL;
}
```

### Run the app

For the best experience with PHP, we recommend setting up two separate files:

1. `subscribe.php` - Handles subscription and message reception
2. `publish.php` - Handles message publishing

To run your PHP application:

1. Open two terminal windows or sessions
2. In the first terminal, run the subscriber script: php subscribe.php
3. In the second terminal, run the publisher script: php publish.php

When running the subscriber, you should see a connection message:

```php
Connected to PubNub!
```

After publishing a message, you should see output similar to:

```php
Received message: {"text":"Hello from PHP SDK!","timestamp":1678912345,"sender":{"name":"PHP Publisher","id":"php-demo"}}
Publisher: php-publisher-demo
Channel: hello_world
Timetoken: 16789123450000000
```

:::note Web environment
If you're working in a web environment, you'll likely need a different approach for subscriptions. Consider using the PubNub JavaScript SDK for real-time browser updates, or implement a polling mechanism to retrieve messages from history.
:::

## Complete example

Here's a complete working example that puts everything together using two separate PHP files.

#### subscribe.php

```php
// Create a new configuration instance
$pnConfiguration = new PNConfiguration();

// Set subscribe key (required)
$pnConfiguration->setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo");

// Set publish key (only required if publishing)
$pnConfiguration->setPublishKey(getenv("PUBLISH_KEY") ?? "demo");

// Set UUID (required to connect)
$pnConfiguration->setUserId("php-sdk-subscriber");

// Set up cryptography for message encryption (optional)
// $pnConfiguration->setCryptoModule(CryptoModule::aesCbcCryptor("your-cipher-key", true));

// Configure connection timeout in seconds
$pnConfiguration->setConnectTimeout(10);

// Create PubNub instance with the configured settings
$pubnub = new PubNub($pnConfiguration);
class MySubscribeCallback extends SubscribeCallback
{
    public function status($pubnub, $status)
    {
        if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
            // This event happens when radio / connectivity is lost
            echo "Unexpected disconnect - network may be down" . PHP_EOL;
        } elseif ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
            // Connect event. You can do stuff like publish, and know you'll get it
            echo "Connected to PubNub!" . PHP_EOL;
        } elseif ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
            // Handle message decryption error
            echo "Decryption error: " . $status->getException() . PHP_EOL;
        }
    }

    public function message($pubnub, $message)
    {
        // Handle new message stored in message.message
        echo "Received message: " . json_encode($message->getMessage()) . PHP_EOL;
        echo "Publisher: " . $message->getPublisher() . PHP_EOL;
        echo "Channel: " . $message->getChannel() . PHP_EOL;
        echo "Timetoken: " . $message->getTimetoken() . PHP_EOL;
    }

    public function presence($pubnub, $presence)
    {
        // Handle incoming presence data
        echo "Presence event: " . $presence->getEvent() . PHP_EOL;
        echo "UUID: " . $presence->getUuid() . PHP_EOL;
        echo "Channel: " . $presence->getChannel() . PHP_EOL;
        echo "Occupancy: " . $presence->getOccupancy() . PHP_EOL;
    }
}

// Add listener
$subscribeCallback = new MySubscribeCallback();
$pubnub->addListener($subscribeCallback);
// Subscribe to a channel, this will block execution
$pubnub->subscribe()
    ->channels("hello_world")
    ->withPresence(true)  // Optional: subscribe to presence events
    ->execute();
```

#### publish.php

```php
// Create configuration with demo keys
$pnConfig = new PNConfiguration();
$pnConfig->setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo");
$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo");
$pnConfig->setUserId("php-publisher-demo");

// Initialize PubNub instance
$pubnub = new PubNub($pnConfig);

try {
    // Create message data
    $messageData = [
        "text" => "Hello from PHP SDK!",
        "timestamp" => time(),
        "sender" => [
            "name" => "PHP Publisher",
            "id" => "php-demo"
        ]
    ];

    // Publish a message to a channel
    $result = $pubnub->publish()
        ->channel("hello_world")              // Channel to publish to
        ->message($messageData)               // Message content
        ->shouldStore(true)                   // Store in history
        ->ttl(15)                             // Time to live (hours)
        ->usePost(true)                       // Use POST method
        ->customMessageType("text-message")   // Custom message type
        ->sync();                             // Execute synchronously

    // Display success message with timetoken
    echo "Message published successfully!" . PHP_EOL;
    echo "Timetoken: " . $result->getTimetoken() . PHP_EOL;

    // Convert timetoken to readable date
    $timestamp = floor($result->getTimetoken() / 10000000);
    $readableDate = date('Y-m-d H:i:s', $timestamp);
    echo "Published at: " . $readableDate . PHP_EOL;

    // Display published message
    echo PHP_EOL . "Published message: " . PHP_EOL;
    echo json_encode($messageData, JSON_PRETTY_PRINT) . PHP_EOL;
} catch (PubNubServerException $exception) {
    // Handle PubNub server-specific errors
    echo "Error publishing message: " . $exception->getMessage() . PHP_EOL;

    if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) {
        echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL;
    }

    if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) {
        echo "Status Code: " . $exception->getStatusCode() . PHP_EOL;
    }
} catch (PubNubException $exception) {
    // Handle PubNub-specific errors
    echo "PubNub Error: " . $exception->getMessage() . PHP_EOL;
} catch (Exception $exception) {
    // Handle general exceptions
    echo "Error: " . $exception->getMessage() . PHP_EOL;
}
```

### Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

| Issue | Possible Solutions |
| --- | --- |
| No connection message | Check your internet connection., Verify your publish and subscribe keys are correct., Make sure you're not behind a firewall blocking PubNub's connections. |
| Message not received | Double-check that you're subscribed to the correct channel., Verify that the message was actually sent (check for any error messages)., Make sure the subscriber is running before publishing messages. |
| Build errors | Ensure you've added the PubNub dependency correctly via Composer., Check that you're using PHP 7.0 or higher., Make sure all imports are correct. |
| Script terminates | For web environments, PHP scripts may timeout. Consider alternative approaches for long-running processes., For CLI scripts, make sure nothing is causing the script to exit. |

## Next steps

Great job! 🎉 You've successfully created your first PubNub application with PHP. Here are some exciting things you can explore next:

### Advanced features

* Try out [Presence](https://www.pubnub.com/docs/sdks/php/api-reference/presence) to track online/offline status.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/php/api-reference/storage-and-playback) to store and retrieve messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/php/api-reference/access-manager) to secure your channels.

### Real examples

* Explore our [PHP SDK GitHub repository](https://github.com/pubnub/php/) for more code samples.
* Look at [examples folder](https://github.com/pubnub/php/tree/master/examples) for sample implementations.

### More help

* Check out the [SDK reference documentation](https://www.pubnub.com/docs/sdks/php/api-reference/configuration) for detailed API information.
* Visit the [support portal](https://support.pubnub.com/) for additional resources.
* Ask the AI assistant (the looking glass icon at the top of the page) for help.

## Terms in this document

* **Publish Key** - A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **Subscribe Key** - A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.