---
source_url: https://www.pubnub.com/docs/sdks/php/api-reference/storage-and-playback
title: Message Persistence API for PHP SDK
updated_at: 2026-05-19T12:13:05.958Z
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


# Message Persistence API for PHP SDK

PubNub PHP SDK, use the latest version: 9.0.0

Install:

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

Message Persistence gives you real-time access to the history of messages published to PubNub. Each message is timestamped to the nearest 10 nanoseconds and stored across multiple availability zones in several geographic locations. You can encrypt stored messages with AES-256 so they are not readable on PubNub’s network. For details, see [Message Persistence](https://www.pubnub.com/docs/general/storage).

You control how long messages are stored through your account’s retention policy. Options include: 1 day, 7 days, 30 days, 3 months, 6 months, 1 year, or Unlimited.

You can retrieve the following:

* Messages
* Message reactions
* Files (using the File Sharing API)

## Fetch history

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Fetch historical messages from one or more channels. Use `includeMessageActions` to include message actions.

You can control how messages are returned and in what order.

* If you specify only the `start` parameter (without `end`), you receive messages older than the `start` timetoken.
* If you specify only the `end` parameter (without `start`), you receive messages from that `end` timetoken and newer.
* If you specify both `start` and `end`, you retrieve messages between those timetokens (inclusive of the `end` value).

You can receive up to 100 messages for a single channel. For multiple channels (up to 500), you can receive up to 25 messages per channel. If more messages match the time range, make iterative calls and adjust the `start` timetoken to page through the results.

### Method(s)

Use the following method(s) in the PHP SDK:

```php
$pubnub.fetchMessages()
    ->channels(string|Array<string>)
    ->maximumPerChannel(Int)
    ->start(string)
    ->end(string)
    ->includeMessageActions(Boolean)
    ->includeMeta(Boolean)
    ->includeMessageType(Boolean)
    ->includeCustomMessageType(Boolean)
    ->includeUuid(Boolean)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channels | string | Yes |  | Channels to fetch history messages from (up to 500). |
| maximumPerChannel | Int | Optional | `25 or 100` | Number of historical messages to return. Default and maximum are 100 (single), 25 (multi), and 25 with `includeMessageActions`. |
| start | string | Optional |  | Timetoken delimiting the start (exclusive) of the time slice. |
| end | string | Optional |  | Timetoken delimiting the end (inclusive) of the time slice. |
| includeMessageActions | Boolean | Optional | `False` | Whether to retrieve history messages with message actions. If `True`, limited to one channel and 25 messages. |
| includeMeta | Boolean | Optional | `False` | Whether to include the meta object (if provided at publish time) in the response. |
| includeMessageType | Boolean | Optional |  | Whether to include message type. See [Retrieving Messages](https://www.pubnub.com/docs/general/storage#retrieve-messages). |
| includeCustomMessageType | Boolean | Optional |  | Whether to include the custom message type. See [Retrieving Messages](https://www.pubnub.com/docs/general/storage#retrieve-messages). |
| includeUuid | Boolean | Optional |  | Whether to receive the publisher `uuid`. |

### Sample code

Retrieve the last message on a 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("fetch-messages-demo-user");

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

try {
    // Fetch the last message from a channel with all additional data
    $result = $pubnub->fetchMessages()
        ->channels("my_channel")                  // Channel to fetch from
        ->includeMessageActions(true)             // Include reactions to messages
        ->includeMeta(true)                       // Include metadata
        ->includeMessageType(true)                // Include message type
        ->includeCustomMessageType(true)          // Include custom message type
        ->includeUuid(true)                       // Include sender UUID
        ->sync();                                 // Execute synchronously

    // Process and display the results
    if (!empty($result->getChannels())) {
        echo "Successfully fetched message history" . PHP_EOL;

        // Display timetoken range
        echo "Start timetoken: " . $result->getStartTimetoken() . PHP_EOL;
        echo "End timetoken: " . $result->getEndTimetoken() . PHP_EOL . PHP_EOL;

        // Process each channel in the result
        foreach ($result->getChannels() as $channelName => $messages) {
            echo "Channel: " . $channelName . PHP_EOL;
            echo "Number of messages: " . count($messages) . PHP_EOL;
            echo "----------------------------" . PHP_EOL;

            // Process each message in the channel
            foreach ($messages as $index => $item) {
                echo "Message #" . ($index + 1) . ":" . PHP_EOL;

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

                // Display message content
                echo "Content: " . json_encode($item->getMessage(), JSON_PRETTY_PRINT) . PHP_EOL;

                // Display sender UUID if available
                if ($item->getUuid()) {
                    echo "Sender: " . $item->getUuid() . PHP_EOL;
                }

                // Display metadata if available
                if ($item->getMetadata()) {
                    echo "Metadata: " . json_encode($item->getMetadata(), JSON_PRETTY_PRINT) . PHP_EOL;
                }

                // Display message type information if available
                if ($item->getMessageType()) {
                    echo "Message Type: " . $item->getMessageType() . PHP_EOL;
                }
                if ($item->getCustomMessageType()) {
                    echo "Custom Message Type: " . $item->getCustomMessageType() . PHP_EOL;
                }

                // Display message actions (reactions) if available
                if ($item->getActions() && count($item->getActions()) > 0) {
                    echo "Message Actions:" . PHP_EOL;
                    foreach ($item->getActions() as $actionType => $actions) {
                        echo "  " . $actionType . ":" . PHP_EOL;
                        foreach ($actions as $actionValue => $users) {
                            echo "    " . $actionValue . ": " . count($users) . " reactions" . PHP_EOL;
                        }
                    }
                }

                echo "----------------------------" . PHP_EOL;
            }
        }
    } else {
        echo "No messages found in the channel." . PHP_EOL;
    }
} catch (PubNubServerException $exception) {
    // Handle PubNub server-specific errors
    echo "Error fetching messages: " . $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;
}
```

### Returns

The `fetchMessages()` operation returns an `PNFetchMessagesResult` which contains the following fields:

#### PNFetchMessagesResult

| Method | Description |
| --- | --- |
| `channels`Type: Array | Array of [PNFetchMessageItem](#pnfetchmessageitem) |
| `startTimetoken`Type: Int | Start timetoken. |
| `endTimetoken`Type: Int | End timetoken. |

#### PNFetchMessageItem

| Method | Description |
| --- | --- |
| `message`Type: string | The message |
| `meta`Type: Any | Meta value |
| `messageType`Type: Any | Type of the message |
| `customMessageType`Type: Any | Custom type of the message |
| `uuid`Type: string | UUID of the sender |
| `timetoken`Type: Int | Timetoken of the message |
| `actions`Type: List | A 3-dimensional List of message actions, grouped by action type and value |

## History

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

This function fetches historical messages of a channel.

It is possible to control how messages are returned and in what order, for example you can:

* Search for messages starting on the newest end of the timeline (default behavior - `reverse` = `false`)
* Search for messages from the oldest end of the timeline by setting `reverse` to `true`.
* Page through results by providing a `start` OR `end` timetoken.
* Retrieve a *slice* of the time line by providing both a `start` AND `end` timetoken.
* Limit the number of messages to a specific quantity using the `count` parameter.

:::tip Start & End parameter usage clarity
If only the `start` parameter is specified (without `end`), you will receive messages that are **older** than and up to that `start` timetoken value. If only the `end` parameter is specified (without `start`) you will receive messages that match that `end` timetoken value and **newer**. Specifying values for both `start` *and* `end` parameters will return messages between those timetoken values (inclusive on the `end` value). Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the `start` timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
:::

### Method(s)

To run `History` you can use the following method(s) in the PHP SDK:

```php
$pubnub->history()
    ->channel(String)
    ->reverse(bool)
    ->includeTimetoken(bool)
    ->start(integer)
    ->end(integer)
    ->count(integer)
    ->sync();
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | Channel to return history messages from. |
| `reverse`Type: BooleanDefault: `false` | Traverse from oldest to newest when set to `true`. |
| `includeTimetoken`Type: BooleanDefault: `false` | Whether to include message timetokens in the response. |
| `start`Type: IntegerDefault: n/a | Timetoken delimiting the start (exclusive) of the time slice. |
| `end`Type: IntegerDefault: n/a | Timetoken delimiting the end (inclusive) of the time slice. |
| `count`Type: IntegerDefault: n/a | Number of historical messages to return. |

:::tip
Using the
reverse
parameter
Messages are always returned sorted in ascending time direction from history regardless of `reverse`. The `reverse` direction matters when you have more than 100 (or `count`, if it's set) messages in the time interval, in which case `reverse` determines the end of the time interval from which it should start retrieving the messages.
:::

### Sample code

Retrieve the last 5 messages on a channel:

```php
        try {
            $result = $this->pubnub->history()
                ->channel($this->demoChannel)
                ->count(5)
                ->includeTimetoken(true)
                ->sync();

            echo "  📊 History Results:\n";
            echo "  - Start Timetoken: " . $result->getStartTimetoken() . "\n";
            echo "  - End Timetoken: " . $result->getEndTimetoken() . "\n";
```

### Response

The `history()` operation returns a `PNHistoryResult` which contains the following operations:

| Method | Description |
| --- | --- |
| `getMessages()`Type: Array | array of messages of type PNHistoryItemResult. See [PNHistoryItemResult](#pnhistoryitemresult) for more details. |
| `getStartTimetoken()`Type: Integer | Start timetoken. |
| `getEndTimetoken()`Type: Integer | End timetoken. |

#### PNHistoryItemResult

| Method | Description |
| --- | --- |
| `getTimetoken()`Type: Integer | `Timetoken` of the message. |
| `getEntry()`Type: Object | Message. |

### Other examples

#### Use history() to retrieve the three oldest messages by retrieving from the time line in reverse

```php
<?php

// This file contains additional code snippets for documentation examples
require_once(__DIR__ . '/../vendor/autoload.php');

use PubNub\PubNub;
use PubNub\PNConfiguration;

$config = new PNConfiguration();
$config->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?: 'demo');
$config->setPublishKey(getenv('PUBLISH_KEY') ?: 'demo');
$config->setSecretKey(getenv('SECRET_KEY') ?: 'demo');
$config->setUserId('snippets-demo');
$pubnub = new PubNub($config);

// MESSAGE PERSISTENCE SNIPPETS

// snippet.history_newer_than_timetoken
$pubnub->history()
    ->channel("my_channel")
    ->start(13847168620721752)
    ->reverse(true)
    ->sync();
// snippet.end

// snippet.history_until_timetoken
$pubnub->history()
    ->channel("my_channel")
    ->count(100)
    ->start(-1)
    ->end(13847168819178600)
    ->reverse(true)
    ->sync();
// snippet.end

// snippet.history_include_timetoken
$pubnub->history()
    ->channel("my_channel")
    ->count(5)
    ->includeTimetoken(true)
    ->sync();
// snippet.end

// snippet.delete_specific_message
$pubnub->deleteMessages()
    ->channel("my_channel")
    ->start(15957709532217050)
    ->end(15957709532217050)
    ->sync();
// snippet.end

// snippet.message_counts_different_timetokens
$pubnub->messageCounts()
    ->channels(["my_channel1", "my_channel2"])
    ->channelsTimetoken([
        "my_channel1" => 15614559062344052,
        "my_channel2" => 15614559062344053
    ])
    ->sync();
// snippet.end

// PRESENCE SNIPPETS

// snippet.here_now_with_state
$result = $pubnub->hereNow()
    ->channels("my_channel")
    ->includeUuids(true)
    ->includeState(true)
    ->sync();
// snippet.end

// snippet.here_now_occupancy_only
$result = $pubnub->hereNow()
    ->channels("my_channel")
    ->includeUuids(false)
    ->includeState(false)
    ->sync();
// snippet.end

// snippet.here_now_channel_groups
$pubnub->hereNow()
    ->channelGroups(["cg1", "cg2", "cg3"])
    ->includeUuids(true)
    ->includeState(true)
    ->sync();
// snippet.end

// snippet.where_now
$result = $pubnub->whereNow()
    ->sync();
// snippet.end

// snippet.where_now_specific_uuid
$result = $pubnub->whereNow()
    ->uuid("his-uuid")
    ->sync();
// snippet.end

// snippet.set_state
$pubnub->setState()
    ->channels(["ch1", "ch2", "ch3"])
    ->state(["age" => 30])
    ->sync();
// snippet.end

// snippet.get_state
$pubnub->getState()
    ->channels(["ch1", "ch2", "ch3"])
    ->sync();
// snippet.end

// snippet.set_state_channel_group
$pubnub->setState()
    ->channelGroups(["cg1", "cg2", "cg3"])
    ->state(["age" => 30])
    ->sync();
// snippet.end

// ACCESS MANAGER V3 SNIPPETS

// snippet.grant_different_access_levels
$pubnub->grantToken()
    ->ttl(15)
    ->authorizedUuid('my-authorized-uuid')
    ->addChannelResources([
        'channel-a' => ['read' => true],
        'channel-b' => ['read' => true, 'write' => true],
        'channel-c' => ['read' => true, 'write' => true],
        'channel-d' => ['read' => true, 'write' => true],
    ])
    ->addChannelGroupResources([
        'channel-group-b' => ['read' => true],
    ])
    ->addUuidResources([
        'uuid-c' => ['get' => true],
        'uuid-d' => ['get' => true, 'update' => true],
    ])
    ->sync();
// snippet.end

// snippet.grant_regex_channels
$pubnub->grantToken()
    ->ttl(15)
    ->authorizedUuid('my-authorized-uuid')
    ->addChannelPatterns([
        '^channel-[A-Za-z0-9]$' => ['read' => true],
    ])
    ->sync();
// snippet.end

// snippet.grant_combined_regex
$pubnub->grantToken()
    ->ttl(15)
    ->authorizedUuid('my-authorized-uuid')
    ->addChannelResources([
        'channel-a' => ['read' => true],
        'channel-b' => ['read' => true, 'write' => true],
        'channel-c' => ['read' => true, 'write' => true],
        'channel-d' => ['read' => true, 'write' => true],
    ])
    ->addChannelGroupResources([
        'channel-group-b' => ['read' => true],
    ])
    ->addUuidResources([
        'uuid-c' => ['get' => true],
        'uuid-d' => ['get' => true, 'update' => true],
    ])
    ->addChannelPatterns([
        '^channel-[A-Za-z0-9]$' => ['read' => true],
    ]);
// snippet.end

// Disabling phpcs to keep token as one line
// phpcs:disable
// snippet.permissions_object_example
$pubnub->parseToken("p0F2AkF0Gl2BEIJDdHRsGGRDcmVzpERjaGFuoENncnCgQ3VzcqBDc3BjoENwYXSkRGNoYW6gQ2dycKBDdXNyomZeZW1wLSoDZl5tZ3ItKhgbQ3NwY6JpXnB1YmxpYy0qA2pecHJpdmF0ZS0qGBtEbWV0YaBDc2lnWCAsvzGmd2rcgtr9rcs4r2tqC87YSppSYqs9CKfaM5IRZA")
    ->getChannelResource('my-channel');
// snippet.end
// phpcs:enable
```

##### Response

```php
PubNub\Models\Consumer\History\PNHistoryResult Object(
    [messages:PubNub\Models\Consumer\History\PNHistoryResult:private] => Array(
        [0] => PubNub\Models\Consumer\History\PNHistoryItemResult Object(
            [entry:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => Array(
                [a] => 11
                [b] => 22
            )
            [crypto:PubNub\Models\Consumer\History\PNHistoryItemResult:private] =>
            [timetoken:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => 1111
        )
        [1] => PubNub\Models\Consumer\History\PNHistoryItemResult Object(
            [entry:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => Array(
                [a] => 33
                [b] => 44
            )
            [crypto:PubNub\Models\Consumer\History\PNHistoryItemResult:private] =>
            [timetoken:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => 2222
        )
        [2] => PubNub\Models\Consumer\History\PNHistoryItemResult Object(
            [entry:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => Array(
                [a] => 55
                [b] => 66
            )
            [crypto:PubNub\Models\Consumer\History\PNHistoryItemResult:private] =>
            [timetoken:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => 2222
        )
    )

    [startTimetoken:PubNub\Models\Consumer\History\PNHistoryResult:private] => 13406746729185766
    [endTimetoken:PubNub\Models\Consumer\History\PNHistoryResult:private] => 13406746780720711
)
```

#### Use history() to retrieve messages newer than a given timetoken by paging from oldest message to newest message starting at a single point in time (exclusive)

```php
$pubnub->history()
    ->channel("my_channel")
    ->start(13847168620721752)
    ->reverse(true)
    ->sync();
```

##### Response

```php
PubNub\Models\Consumer\History\PNHistoryResult Object(
    [messages:PubNub\Models\Consumer\History\PNHistoryResult:private] => Array(
        [0] => PubNub\Models\Consumer\History\PNHistoryItemResult Object(
            [entry:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => Array
                (
                    [a] => 11
                    [b] => 22
                )

            [crypto:PubNub\Models\Consumer\History\PNHistoryItemResult:private] =>
            [timetoken:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => 1111
        )
        [1] => PubNub\Models\Consumer\History\PNHistoryItemResult Object(
            [entry:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => Array(
                [a] => 33
                [b] => 44
            )

            [crypto:PubNub\Models\Consumer\History\PNHistoryItemResult:private] =>
            [timetoken:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => 2222
        )
        [2] => PubNub\Models\Consumer\History\PNHistoryItemResult Object(
            [entry:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => Array(
                [a] => 55
                [b] => 66
            )

            [crypto:PubNub\Models\Consumer\History\PNHistoryItemResult:private] =>
            [timetoken:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => 2222
        )

    )

    [startTimetoken:PubNub\Models\Consumer\History\PNHistoryResult:private] => 13406746729185766
    [endTimetoken:PubNub\Models\Consumer\History\PNHistoryResult:private] => 13406746780720711
)
```

#### Use history() to retrieve messages until a given timetoken by paging from newest message to oldest message until a specific end point in time (inclusive)

```php
$pubnub->history()
    ->channel("my_channel")
    ->count(100)
    ->start(-1)
    ->end(13847168819178600)
    ->reverse(true)
    ->sync();
```

##### Response

```php
PubNub\Models\Consumer\History\PNHistoryResult Object(
    [messages:PubNub\Models\Consumer\History\PNHistoryResult:private] => Array(
        [0] => PubNub\Models\Consumer\History\PNHistoryItemResult Object(
            [entry:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => Array(
                [a] => 11
                [b] => 22
            )

            [crypto:PubNub\Models\Consumer\History\PNHistoryItemResult:private] =>
            [timetoken:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => 1111
        )
        [1] => PubNub\Models\Consumer\History\PNHistoryItemResult Object(
            [entry:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => Array(
                [a] => 33
                [b] => 44
            )

            [crypto:PubNub\Models\Consumer\History\PNHistoryItemResult:private] =>
            [timetoken:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => 2222
        )
        [2] => PubNub\Models\Consumer\History\PNHistoryItemResult Object(
            [entry:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => Array(
                [a] => 55
                [b] => 66
            )

            [crypto:PubNub\Models\Consumer\History\PNHistoryItemResult:private] =>
            [timetoken:PubNub\Models\Consumer\History\PNHistoryItemResult:private] => 2222
        )

    )

    [startTimetoken:PubNub\Models\Consumer\History\PNHistoryResult:private] => 13406746729185766
    [endTimetoken:PubNub\Models\Consumer\History\PNHistoryResult:private] => 13406746780720711
)
```

#### Include timetoken in history response

```php
$pubnub->history()
    ->channel("my_channel")
    ->count(100)
    ->includeTimetoken(true)
    ->sync();
```

## Delete messages from history

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Remove messages from the history of a specific channel.

:::note Required setting
Enable `Delete-From-History` for your key in the Admin Portal and initialize the SDK with a secret key.
:::

### Method(s)

To `Delete Messages from History` you can use the following method(s) in the PHP SDK.

```php
$pubnub->deleteMessages()
    ->channel(String)
    ->start(integer)
    ->end(integer)
    ->sync()
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | Channel to delete messages from. |
| `start`Type: IntegerDefault: n/a | Timetoken delimiting the start (inclusive) of the time slice. |
| `end`Type: IntegerDefault: n/a | Timetoken delimiting the end (exclusive) of the time slice. |

### Sample code

```php
            try {
                $this->pubnub->deleteMessages()
                    ->channel($this->demoChannel)
                    ->start($startTimetoken)
                    ->end($endTimetoken)
                    ->sync();

                echo "  ✅ Delete operation completed successfully\n";
                echo "  Note: Message deletion may take a moment to reflect in history\n";
            } catch (PubNubException $e) {
```

### Other examples

#### Delete specific message from history

To delete a specific message, pass the `publish timetoken` (received from a successful publish) in the `End` parameter and `timetoken +/- 1` in the `Start` parameter. For example, if `15526611838554310` is the `publish timetoken`, pass `15526611838554309` in `Start` and `15526611838554310` in `End` parameters respectively as shown in the following code snippet.

```php
$pubnub->deleteMessages()
    ->channel("my_channel")
    ->start(15957709532217050)
    ->end(15957709532217050)
    ->sync();
```

## Message counts

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Return the number of messages published since the given time. The count is the number of messages with a timetoken greater than or equal to the value in `channelsTimetoken`.

:::note Unlimited message retention
Only messages from the last 30 days are counted.
:::

### Method(s)

You can use the following method(s) in the PHP SDK:

```php
$pubnub->messageCounts()
    ->channels(array)
    ->channelsTimetoken(array)
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: ArrayDefault: n/a | Channels to fetch the message count. |
| `channelsTimetoken` *Type: ArrayDefault: n/a | Array in the same order as channels; a single timetoken applies to all channels; otherwise, lengths must match or the function returns a `PNStatus` error. |

### Sample code

```php
                min($this->publishedTimetokens) : "0";

            $result = $this->pubnub->messageCounts()
                ->channels([$this->demoChannel])
                ->channelsTimetoken([$oldestTimetoken])
                ->sync();

            echo "  📊 Message Count Results:\n";
            $channels = $result->getChannels();

            foreach ($channels as $channelName => $count) {
                echo "    Channel '$channelName': $count messages\n";
```

### Returns

The operation returns a `PNMessageCountsResult` which contains the following operations

| Method | Description |
| --- | --- |
| `getChannels()`Type: Array | An associative array with channel name as key and messages count as value. `Channels` without messages have a count of 0. `Channels` with 10,000 messages or more have a count of 10000. |

### Other examples

#### Retrieve count of messages using different timetokens for each channel

```php
$pubnub->messageCounts()
    ->channels(["my_channel1", "my_channel2"])
    ->channelsTimetoken([
        "my_channel1" => 15614559062344052,
        "my_channel2" => 15614559062344053
    ])
    ->sync();
```

## Terms in this document

* **Message** - A unit of data transmitted between clients or between a client and a server in PubNub, containing information such as text, binary data, or structured data formats like JSON. Messages are sent over channels and can be tracked for delivery and read status.
* **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.