---
source_url: https://www.pubnub.com/docs/sdks/php/api-reference/configuration
title: Configuration API for PHP SDK
updated_at: 2026-06-23T11:45:27.073Z
sdk_name: PubNub PHP SDK
sdk_version: 9.0.1
---

> 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


# Configuration API for PHP SDK

PubNub PHP SDK, use the latest version: 9.0.1

Install:

```bash
composer require pubnub/pubnub@9.0.1
```

Complete API reference for building real-time applications on PubNub with the PHP Software Development Kit (SDK). This page covers configuration, initialization, and event handling with concise, working examples.

## Configuration

`PNConfiguration` stores user-provided settings that control PubNub client behavior. It includes additional properties for precise client configuration.

:::warning Immutable configuration
Once a configuration object has been passed to the PubNub constructor, you can't change its properties.
Although we don't recommend it, you can enable changing the configuration object after using it to create a PubNub instance, by calling the `disableImmutableCheck()` method just before passing it to the PubNub constructor.
```php
$config = new PNConfiguration();
$config->setPublishKey('demo');
$config->setSubscribeKey('demo');
$config->setUserId('demo');
// not recommended, disables config immutability
$config->disableImmutableCheck();
$pn = new PubNub($config);
```
:::

### Method(s)

To create a configuration instance, use the following constructor in the PHP SDK:

```php
new PNConfiguration();
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| subscribeKey | String | Yes |  | `subscribeKey` from Admin Portal |
| publishKey | String | Optional | `null` | `publishKey` from Admin Portal (only required if publishing) |
| secretKey | String | Optional | `null` | `secretKey` (only required for modifying/revealing access permissions) |
| UserId | String | Yes |  | `UUID` to use. You should set a unique `UUID` to identify the user or the device that connects to PubNub. It's a UTF-8 encoded string of up to 92 alphanumeric characters. If you don't set the `UUID`, you won't be able to connect to PubNub. |
| authKey | String | Optional | `null` | If Access Manager is utilized, client will use this `authKey` in all restricted requests. |
| ssl | Boolean | Optional | `true` | Use Secure Sockets Layer (SSL). |
| connectTimeout | Integer | Optional | `10` | How long to wait before giving up connection to client. The value is in seconds. |
| subscribeTimeout | Integer | Optional | `310` | How long to keep the `subscribe` loop running before disconnect. The value is in seconds. |
| nonSubscribeRequestTimeout | Integer | Optional | `10` | On `non subscribe` operations, how long to wait for server response. The value is in seconds. |
| filterExpression | String | Optional | `null` | Feature to subscribe with a custom filter expression. |
| origin | String | Optional | `ps.pndsn.com` | Custom `origin` if needed. To request a custom domain, contact support and follow the [request process](https://www.pubnub.com/docs/general/setup/data-security#request-process). |
| cipherKey | String | Optional | `null` | If `cipherKey` is passed, all communications to/from PubNub will be encrypted. |
| useRandomIV | Boolean | Optional | `true` | When `true` the initialization vector (IV) is random for all requests (not just for file upload). When `false` the IV is hard-coded for all requests except for file upload. |
| client | ClientInterface | Optional | `Guzzle HTTP client` | Custom HTTP client implementing PSR-18. If not set, the default Guzzle client is used. For more information on implementing a custom HTTP client, refer to [PHP 8.0.0 migration guide](https://www.pubnub.com/docs/sdks/php/migration-guides/php-v8-migration-guide). |
| crypto | PubNubCryptoCore | Optional |  | The cryptography module used for encryption and decryption of messages and files. Takes the `cipherKey` and `useRandomIV` parameters as arguments. For detailed encryption configuration and examples, refer to the [Encryption API](https://www.pubnub.com/docs/sdks/php/api-reference/encryption) page. |

:::warning Disabling random initialization vector
Disable random initialization vector (IV) only for backward compatibility (<`4.3.0`) with existing applications. Never disable random IV on new applications.
:::

#### crypto module

`crypto` encrypts and decrypts messages and files. From 6.1.0, you can configure the algorithms it uses.

Each SDK includes two options: legacy 128-bit encryption and recommended 256-bit AES-CBC. For background, see [Message Encryption](https://www.pubnub.com/docs/general/setup/data-security#message-encryption).

For configuration details, examples, and partial encryption methods, see [Encryption](https://www.pubnub.com/docs/sdks/php/api-reference/encryption).

:::note Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.
:::

### Sample code

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```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-example-user");

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

// Set authentication key (optional, required only when using Access Manager)
// $pnConfiguration->setAuthKey("my_auth_key");

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

// Configure subscribe request timeout in seconds
$pnConfiguration->setSubscribeTimeout(310);

// Configure non-subscribe request timeout in seconds
$pnConfiguration->setNonSubscribeRequestTimeout(10);

// Set filter expression (optional)
// $pnConfiguration->setFilterExpression("channel == 'my-channel'");

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

// Display configuration information
echo "PubNub Configuration:\n";
echo "Subscribe Key: " . $pnConfiguration->getSubscribeKey() . "\n";
echo "Publish Key: " . $pnConfiguration->getPublishKey() . "\n";
echo "User ID: " . $pnConfiguration->getUserId() . "\n";
echo "Encryption: " . ($pnConfiguration->getCryptoSafe() ? "enabled" : "disabled") . "\n";

// Now you can use this PubNub instance to publish and subscribe

// Example: Create a simple message
$message = ["text" => "Hello from PHP SDK!"];

// Example: Publish the message (uncomment to execute)
/*
$pubnub->publish()
    ->channel("demo-channel")
    ->message($message)
    ->sync();

echo "Message published to 'demo-channel'\n";
*/

// Keep this code running only if you plan to subscribe to messages
// Otherwise, the script will exit after publishing
```

### Rest response from server

Returns a client configuration that is ready to use.

## Initialization

Add PubNub to your project using the steps in the [Getting Started guide](https://www.pubnub.com/docs/sdks/php).

#### Use PHP SDK in your code

```php
use PubNub\PubNub;
```

PEM files can be downloaded for the domains `pubsub.pubnub.com`, `pubsub.pubnub.net` and `ps.pndsn.com` using the commands:

```bash
echo Q | openssl s_client -connect pubsub.pubnub.com:443 -servername pubsub.pubnub.com -showcerts
echo Q | openssl s_client -connect pubsub.pubnub.net:443 -servername pubsub.pubnub.net -showcerts
echo Q | openssl s_client -connect ps.pndsn.com:443 -servername ps.pndsn.com -showcerts
```

Set `verify_peer` to `true` to use the PEM files.

### Description

This function initializes the PubNub Client API context. Call it before using any APIs to establish account-level credentials such as `publishKey` and `subscribeKey`.

### Method(s)

To `Initialize` PubNub you can use the following method(s) in the PHP SDK:

```php
new PubNub($pnconf);
```

| Parameter | Description |
| --- | --- |
| `pnConfiguration` *Type: PNConfiguration | Go to [Configuration](#configuration) for more details. |

### Sample code

#### Initialize the PubNub client API

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```php
$pnconf = new PNConfiguration();

$pnconf->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?: 'demo');
$pnconf->setPublishKey(getenv('PUBLISH_KEY') ?: 'demo');
$pnconf->setSecure(false);
$pnconf->setUserId("myUniqueUserId");
$pubnub = new PubNub($pnconf);
```

### Returns

Returns a PubNub instance for APIs like `publish()`, `subscribe()`, `history()`, and `hereNow()`.

### Other examples

#### Initialize a non-secure client

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```php
$pnConfiguration = new PNConfiguration();

$pnConfiguration->setSubscribeKey("my_sub_key");
$pnConfiguration->setPublishKey("my_pub_key");
$pnConfiguration->setSecure(false);
$pnConfiguration->setUserId("myUniqueUserId");
$pubnub = new PubNub($pnConfiguration);
```

#### Initialization for a Read-Only client

In the case where a client will only read messages and never publish to a channel, you can simply omit the `publishKey` when initializing the client:

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```php
$pnConfiguration = new PNConfiguration();

$pnConfiguration->setUserId("myUniqueUserId");
$pnConfiguration->setSubscribeKey("my_sub_key");

$pubnub = new PubNub($pnConfiguration);
```

#### Use a custom UUID

Set a custom `UserId` to identify your users.

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```php
$pnconf = new PNConfiguration();

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

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

#### Initializing with Access Manager

:::note Requires Access Manager add-on
This method requires that the *Access Manager* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

:::note Secure your secretKey
Anyone with the `secretKey` can grant and revoke permissions to your app. Never let your secret key be discovered, and to only exchange it / deliver it securely. Only use the `secretKey` on secure server-side platforms.
When you init with `secretKey`, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.
:::

For applications that will administer Access Manager permissions, the API is initialized with the `secretKey` as in the following example:

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```php
$pnConfiguration = new PNConfiguration();

$pnConfiguration->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?: 'demo');
$pnConfiguration->setPublishKey(getenv('PUBLISH_KEY') ?: 'demo');
//NOTE: only server side should have secret key
$pnConfiguration->setSecretKey(getenv('SECRET_KEY') ?: 'demo');
$pnConfiguration->setUserId("myUniqueUserId");
$pubnub = new PubNub($pnConfiguration);
```

Now that the pubnub object is instantiated the client will be able to access the Access Manager functions. The pubnub object will use the `secretKey` to sign all Access Manager messages to the PubNub Network.

## Event listeners

Listeners notify your app about connection status, messages, and presence events.

Add listeners before you call methods.

#### Add listeners

```php
class MySubscribeCallback extends SubscribeCallback
{
    function status($pubnub, $status)
    {
        if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
        // This event happens when connectivity is lost
        } elseif ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
        // Connect event. You can do stuff like publish, and know you'll get it
        } elseif ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
        // Handle message decryption error.
        }
    }

    function message($pubnub, $message)
    {
    // Handle new message stored in message.message
    }
    function presence($pubnub, $presence)
    {
    // handle incoming presence data
    }
}

$pnconf = new PNConfiguration();

$pnconf->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?: 'demo');
$pnconf->setPublishKey(getenv('PUBLISH_KEY') ?: 'demo');
$pnconf->setUserId("event-listener-demo-user");

$pubnub = new PubNub($pnconf);

$subscribeCallback = new MySubscribeCallback();

$pubnub->addListener($subscribeCallback);

// Subscribe to a channel, this is not async.
// Note: This would block
// $pubnub->subscribe()
// ->channels("hello_world")
// ->execute();

// Use the publish command separately from the Subscribe code shown above.
// Subscribe is not async and will block the execution until complete.
// Note: Commented out for testing to avoid network calls
// $result = $pubnub->publish()
// ->channel("hello_world")
// ->message("Hello PubNub")
// ->sync();
//
// // Verify publish result
// assert($result->getTimetoken() > 0);
//
// print_r($result);
```

#### Remove listeners

```php
$subscribeCallback = new MySubscribeCallback();

$pubnub->addListener($subscribeCallback);

// some time later
$pubnub->removeListener($subscribeCallback);
```

#### Listener status events

| Category | Description |
| --- | --- |
| `PNConnectedCategory` | SDK subscribed with a new mix of channels (fired every time the `channel` / `channel group` mix changed). |
| `PNAccessDeniedCategory` | Request failed because of access error (active Access Manager). `status.errorData.channels` or `status.errorData.channelGroups` contain list of channels and/or groups to which user with specified `auth` key doesn't have access. |
| `PNMalformedResponseCategory` | Request received in response non-JSON data. It can be because of publish WiFi hotspot which require authorization or proxy server message. |
| `PNBadRequestCategory` | Request can't be completed because not all required values has been passed or passed values has unexpected data type. |
| `PNDecryptionErrorCategory` | Message Persistence API may return this status if some messages can't be decrypted. The unencrypted message is returned in `status.associatedObject` (`PNMessageData`), which contains channel and message properties. |
| `PNTimeoutCategory` | Used API didn't receive a response from the server in time. |
| `PNUnknownCategory` | No specific category was assigned to the request. |
| `PNUnexpectedDisconnectCategory` | The SDK can't reach PubNub servers due to connectivity issues (for example, device offline, ISP problems, or proxy). |
| `PNCancelledCategory` | Request was cancelled by user. |
| `PNUnknownCategory` | Unknown error happened. |

## UserId

These functions are used to set/get a user ID on the fly.

### Property(s)

To set/get `UserId` you can use the following property(s) in PHP SDK:

#### Set UserId

```php
$pnconf->setUserId(string);
```

| Parameter | Description |
| --- | --- |
| `UserId` *Type: StringDefault: n/a | `UserId` to be used as a device identifier. If you don't set the `UserId`, you won't be able to connect to PubNub. |

#### Get UserId

```php
$pnconf->getUserId();
```

This method doesn't take any arguments.

### Sample code

#### Set UserId

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```php
$pnconf = new PNConfiguration();
$pnconf->setUserId("myUniqueUserId");
```

#### Get UserId

```php
$pubnub->getConfiguration()
    ->getUserId();
```

## Authentication key

Setter and getter for users auth key.

#### Set auth key

```php
$pnconf->setAuthKey(string);
```

| Parameter | Description |
| --- | --- |
| `AuthKey` *Type: String | If Access Manager is utilized, client will use this `authkey` in all restricted requests. |

#### Get auth key

```php
$pnconf->getAuthKey();
```

This method doesn't take any argument.

### Sample code

#### Set auth key

```php
$pubnub->getConfiguration()
    ->setAuthKey("my_newauthkey");
```

#### Get auth key

```php
$pubnub->getConfiguration()
    ->getAuthKey();
```

### Returns

None.

## Filter expression

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.

To set or get message filters, you can use the following methods. To learn more about filtering, refer to the [Publish Messages](https://www.pubnub.com/docs/general/messages/publish) documentation.

### Method(s)

#### Set filter expression

```php
setFilterExpression( string filterExpression )
```

| Parameter | Description |
| --- | --- |
| `filterExpression` *Type: string | Logical expression to be evaluated on PubNub servers |

#### Get filter expression

```php
getFilterExpression
```

This method doesn't take any arguments.

### Sample code

#### Set filter expression

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```php
$pnconf = new PNConfiguration();

$pnconf->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?: 'demo');
$pnconf->setUserId("filter-demo-user");
$pnconf->setFilterExpression("userid == 'my_userid'");

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

#### Get filter expression

```php
$pubnub->getConfiguration()->getFilterExpression();
```

## Terms in this document

* **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.