---
source_url: https://www.pubnub.com/docs/sdks/php/api-reference/presence
title: Presence API for PHP SDK
updated_at: 2026-06-19T11:38:06.548Z
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


# Presence API for PHP SDK

PubNub PHP SDK, use the latest version: 9.0.0

Install:

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

Presence lets you track who is online or offline and store custom state information. Presence shows:

* When a user has joined or left a channel
* How many users are subscribed to a particular channel (occupancy)
* Which channels a user or device is subscribed to
* Presence state associated with these users

Learn more about our Presence feature in the [Presence overview](https://www.pubnub.com/docs/general/presence/overview).

## Here now

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

This method returns information about the current state of a channel, including a list of unique user IDs (universally unique identifiers, UUIDs) currently subscribed to the channel and the total occupancy count of the channel.

:::note Cache
This method has a 3-second response cache time.
:::

### Method(s)

To call `Here Now` you can use the following method(s) in the PHP SDK:

```php
$pubnub->hereNow()
    ->channels(string|array)
    ->channelGroups(string|array)
    ->includeState(boolean)
    ->includeUuids(boolean)
    ->limit(int)
    ->offset(int)
    ->sync();
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channels | String|Array | Optional |  | The `channels` to get the `here now` details. |
| channelGroups | String|Array | Optional |  | The `channel groups` to get the `here now` details. Wildcards are not supported. |
| includeState | Boolean | Optional | `false` | If `true`, the response will include the presence states of the users for `channels`/`channelGroups`. |
| includeUuids | Boolean | Optional | `true` | If `true`, the response will include the `UUIDs` of the connected clients. |
| limit | Integer | Optional | `1000` | Maximum number of occupants to return per channel. Valid range: `0-1000`. Use `0` to get occupancy counts without user details. |
| offset | Integer | Optional |  | Zero-based starting index for pagination. Returns occupants starting from this position in the list. Must be `>= 0`. Requires `limit > 0`. Use with `limit` to paginate through large occupant lists. |

### Sample code

#### Get a list of UUIDs subscribed to channel

:::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
<?php

// Include Composer autoloader (adjust path if needed)
require_once 'vendor/autoload.php';

use PubNub\PNConfiguration;
use PubNub\PubNub;
use PubNub\Exceptions\PubNubServerException;
use PubNub\Exceptions\PubNubException;

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

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

try {
    // Get presence information for specified channels
    $result = $pubnub->hereNow()
        ->channels(["my_channel", "demo"])
        ->includeUuids(true)  // Include the UUIDs of connected clients
        ->includeState(false) // Don't include state information
        ->limit(100)          // Optional: Limit occupants returned per channel (0-1000, default: 1000)
        ->offset(0)           // Optional: Skip first N occupants for pagination (default: 0)
        ->sync();

    // Display total counts
    echo "Total channels with presence: " . $result->getTotalChannels() . PHP_EOL;
    echo "Total users online: " . $result->getTotalOccupancy() . PHP_EOL;

    // Iterate through each channel
    foreach ($result->getChannels() as $channelData) {
        echo PHP_EOL . "Channel: " . $channelData->getChannelName() . PHP_EOL;
        echo "Occupancy: " . $channelData->getOccupancy() . " users" . PHP_EOL;

        // List all users in the channel
        if ($channelData->getOccupancy() > 0) {
            echo "Users present:" . PHP_EOL;

            foreach ($channelData->getOccupants() as $index => $occupant) {
                echo ($index + 1) . ". UUID: " . $occupant->getUuid() . PHP_EOL;

                // Display state if available and requested
                if ($occupant->getState()) {
                    echo "   State: " . json_encode($occupant->getState()) . PHP_EOL;
                }
            }
        } else {
            echo "No users currently in this channel" . PHP_EOL;
        }
    }

    // Example: How to use the result in your application
    echo PHP_EOL . "Example usage:" . PHP_EOL;
    echo "- Track how many users are in each channel" . PHP_EOL;
    echo "- Display a list of active users" . PHP_EOL;
    echo "- Check if a specific user is online" . PHP_EOL;
} catch (PubNubServerException $exception) {
    // Handle PubNub-specific errors
    echo "Error getting presence information: " . $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 general PubNub exceptions
    echo "PubNub Error: " . $exception->getMessage() . PHP_EOL;
} catch (Exception $exception) {
    // Handle other exceptions
    echo "Error: " . $exception->getMessage() . PHP_EOL;
}
```

### Response

The `hereNow()` operation returns a `PNHereNowResult` which contains the following fields:

| Method | Description |
| --- | --- |
| `getTotalChannels()`Type: Integer | Total `Channels`. |
| `getTotalOccupancy()`Type: Integer | Total `Occupancy`. |
| `getChannels()`Type: Array | A array with values of `PNHereNowChannelData` for each `channel`. See [PNHereNowChannelData](#pnherenowchanneldata) for more details. |

#### PNHereNowChannelData

| Method | Description |
| --- | --- |
| `getChannelName()`Type: String | `Channel` name. |
| `getOccupancy()`Type: Integer | `Occupancy` of the `channel`. |
| `getOccupants()`Type: Array | A array of `PNHereNowOccupantData`, see [PNHereNowOccupantData](#pnherenowoccupantdata) for more details. |

#### PNHereNowOccupantData

| Method | Description |
| --- | --- |
| `getUuid()`Type: String | `UUID` of the user. |
| `getState()`Type: Array | `State` of the user. |

### Other examples

#### Returning state

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

```php
$result = $pubnub->hereNow()
    ->channels("my_channel")
    ->includeUuids(true)
    ->includeState(true)
    ->sync();
```

##### Example response

```php
PubNub\Models\Consumer\Presence\PNHereNowResult Object(
    [totalChannels:protected] => 2
    [totalOccupancy:protected] => 3
    [channels:protected] => Array(
        [0] => PubNub\Models\Consumer\Presence\PNHereNowChannelData Object(
            [channelName:protected] => ch1
            [occupancy:protected] => 1
            [occupants:protected] => Array(
                [0] => PubNub\Models\Consumer\Presence\PNHereNowOccupantsData Object(
                    [uuid:protected] => user1
                    [state:protected] =>
                )
            )
        )
        [1] => PubNub\Models\Consumer\Presence\PNHereNowChannelData Object(
            [channelName:protected] => ch2
            [occupancy:protected] => 2
            [occupants:protected] => Array(
                [0] => PubNub\Models\Consumer\Presence\PNHereNowOccupantsData Object(
                    [uuid:protected] => user1
                    [state:protected] =>
                )
                [1] => PubNub\Models\Consumer\Presence\PNHereNowOccupantsData Object(
                    [uuid:protected] => user3
                    [state:protected] =>
                )
            )
        )
    )
    )
```

#### Return occupancy only

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

You can return only the `occupancy` information for a single channel by specifying the channel and setting `UUIDs` to false:

```php
$result = $pubnub->hereNow()
    ->channels("my_channel")
    ->includeUuids(false)
    ->includeState(false)
    ->sync();
```

##### Example response

```php
PubNub\Models\Consumer\Presence\PNHereNowResult Object(
    [totalChannels:protected] => 2
    [totalOccupancy:protected] => 3
    [channels:protected] => Array(
        [0] => PubNub\Models\Consumer\Presence\PNHereNowChannelData Object(
            [channelName:protected] => ch1
            [occupancy:protected] => 1
            [occupants:protected] => Array(
                [0] => PubNub\Models\Consumer\Presence\PNHereNowOccupantsData Object(
                    [uuid:protected] => user1
                    [state:protected] =>
                )
            )
        )
        [1] => PubNub\Models\Consumer\Presence\PNHereNowChannelData Object(
            [channelName:protected] => ch2
            [occupancy:protected] => 2
            [occupants:protected] => Array(
                [0] => PubNub\Models\Consumer\Presence\PNHereNowOccupantsData Object(
                    [uuid:protected] => user1
                    [state:protected] =>
                )
                [1] => PubNub\Models\Consumer\Presence\PNHereNowOccupantsData Object(
                    [uuid:protected] => user3
                    [state:protected] =>
                )
            )
        )
    )
)
```

#### Here now for channel groups

```php
$pubnub->hereNow()
    ->channelGroups(["cg1", "cg2", "cg3"])
    ->includeUuids(true)
    ->includeState(true)
    ->sync();
```

##### Example response

```php
(
    [totalChannels:protected] => 1
    [totalOccupancy:protected] => 4
    [channels:protected] => Array(
        [0] => PubNub\Models\Consumer\Presence\PNHereNowChannelData Object(
            [channelName:protected] => ch1
            [occupancy:protected] => 1
            [occupants:protected] => Array(
                [0] => PubNub\Models\Consumer\Presence\PNHereNowOccupantsData Object(
                    [uuid:protected] => 123123234t234f34fq3dq
                    [state:protected] =>
                )
                [1] => PubNub\Models\Consumer\Presence\PNHereNowOccupantsData Object(
                    [uuid:protected] => 143r34f34t34fq34q34q3
                    [state:protected] =>
                )
                [2] => PubNub\Models\Consumer\Presence\PNHereNowOccupantsData Object(
                    [uuid:protected] => 23f34d3f4rq34r34rq23q
                    [state:protected] =>
                )
                [3] => PubNub\Models\Consumer\Presence\PNHereNowOccupantsData Object(
                    [uuid:protected] => w34tcw45t45tcw435tww3
                    [state:protected] =>
                )
            )
        )
    )
    )
```

## Where now

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

This method returns the list of channels a UUID is subscribed to.

:::note Timeout events
If the app restarts (or the page refreshes) within the heartbeat window, no timeout event is generated.
:::

### Method(s)

To call `whereNow()` you can use the following method(s) in the PHP SDK:

```php
$pubnub->whereNow()
    ->uuid(string)
    ->sync();
```

| Parameter | Description |
| --- | --- |
| `uuid`Type: StringDefault: n/a | `Uuid` of the user we want to spy on. |

### Sample code

```php
$result = $pubnub->whereNow()
    ->sync();
```

### Rest response from server

The `whereNow()` function returns a list of channels a `uuid` is subscribed to.

* `channels:["String","String", ... ,"String"]` - List of channels a `uuid` is subscribed to.

#### Example response

```json
{
    "channels": [
        "lobby",
        "game01",
        "chat"
    ]
}
```

### Other examples

```php
$result = $pubnub->whereNow()
    ->uuid("his-uuid")
    ->sync();
```

## User state

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

Clients can set a dynamic custom state (score, game state, location) for their users on one or more channels and store it on a channel as long as the user stays subscribed.

The state is not persisted, and when the client disconnects, the state data is lost. For more information, refer to [Presence State](https://www.pubnub.com/docs/general/presence/presence-state).

### Method(s)

**Set State:** [](#set-state-arguments)

```php
$pubnub->setState()
    ->channels(string|array)
    ->channelGroups(string|array)
    ->state(array)
    ->sync();
```

| Parameter | Description |
| --- | --- |
| `channels`Type: String|Array | `channels` to set `state`. |
| `channelGroups`Type: String|Array | `channel groups` to set `state`. |
| `state`Type: Array | `State` to set. |

**Get state:** [](#get-state-arguments)

```php
$pubnub->getState()
    ->channels(string|array)
    ->channelGroups(string|array)
    ->uuid(string)
    ->sync();
```

| Parameter | Description |
| --- | --- |
| `channels`Type: String|Array | `channels` to get `state`. |
| `channelGroups`Type: String|Array | `channel groups` to get `state`. |
| `uuid`Type: String | `uuid` |

### Sample code

#### Set state

```php
$pubnub->setState()
    ->channels(["ch1", "ch2", "ch3"])
    ->state(["age" => 30])
    ->sync();
```

#### Get state

```php
$pubnub->getState()
    ->channels(["ch1", "ch2", "ch3"])
    ->sync();
```

### Response

The `setState()` operation returns a `PNSetStateResult` which contains the following fields:

| Method | Description |
| --- | --- |
| `setState()`Type: Array | Array of `UUIDs` and the user states. |

The `getState()` operation returns a `PNGetStateResult` which contains the following fields:

| Method | Description |
| --- | --- |
| `getChannels()`Type: Array | Array of `channels` and the user states. |

### Other examples

#### Set state for channels in a channel group

```php
$pubnub->setState()
    ->channelGroups(["cg1", "cg2", "cg3"])
    ->state(["age" => 30])
    ->sync();
```