---
source_url: https://www.pubnub.com/docs/sdks/php/api-reference/files
title: File Sharing API for PHP SDK
updated_at: 2026-06-04T11:12:29.003Z
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


# File Sharing API for PHP SDK

PubNub PHP SDK, use the latest version: 9.0.0

Install:

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

You can upload and share files up to 5 MB on PubNub. Common uses include sharing images in chat apps and documents in healthcare.

When a file is uploaded on a `channel`, it's stored and managed using a storage service, and associated with your key. Subscribers to that `channel` receive a file event which contains a file `ID`, `filename`, and optional `description`.

## Send file

Upload the file to a specified channel.

This method covers the entire process of sending a file, including preparation, uploading the file to a cloud storage service, and post-uploading messaging on a channel.

For the last messaging step, `sendFile` internally calls the [publishFileMessage](#publish-file-message) method to publish a message on the channel.

The published message contains metadata about the file, such as the file identifier and name, enabling others on the channel to find out about the file and access it.

For details on the method that publishes the file message, see [Publish file message](#publish-file-message).

### Method(s)

```php
$pubnub->sendFile()
    ->channel(string)
    ->fileName(string)
    ->message(string|array)
    ->shouldStore(Boolean)
    ->shouldCompress(Boolean)
    ->ttl(Int)
    ->fileHandle(Resource)
    ->fileContent(bytes|File)
    ->meta(string|array)
    ->customMessageType(string)
    ->sync();
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | string | Yes |  | Channel for the file. |
| fileName | string | Yes |  | Name of the file to send. |
| message | string | Optional |  | Message to send along with the file to the specified `channel`. |
| shouldStore | Boolean | Optional | `True` | Whether to store the published `file message` in the `channel` history. |
| shouldCompress | Boolean | Optional | `True` | Whether to compress the request payload. |
| ttl | Integer | Optional |  | How long the message should be stored in the channel's storage. |
| fileHandle | Resource | Yes |  | Pointer to a resource to be read and placed in the buffer. |
| fileContent | bytes | Yes |  | Input stream with file content. |
| meta | string | Optional |  | Metadata object which can be used with the filtering ability. |
| customMessageType | string | Optional |  | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes `-` and underscores `_` are allowed. The value cannot start with special characters or the string `pn_` or `pn-`. Examples: `text`, `action`, `poll`. |

### Sample code

:::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
$channelName = "file-channel";
$testFileName = "pn.gif";

$config = new PNConfiguration();
$config->setSubscribeKey(getenv('SUBSCRIBE_KEY', 'demo'));
$config->setPublishKey(getenv('PUBLISH_KEY', 'demo'));
$config->setUserId('example');

$pubnub = new PubNub($config);
$fileHandle = fopen(__DIR__ . DIRECTORY_SEPARATOR . $testFileName, "r");
$sendFileResult = $pubnub->sendFile()
    ->channel($channelName)
    ->fileName($testFileName)
    ->message("Hello from PHP SDK")
    ->fileHandle($fileHandle)
    ->sync();
fclose($fileHandle);
$fileId = $sendFileResult->getFileId();
$fileName = $sendFileResult->getFileName();

print("File uploaded successfully: {$fileName} with ID: {$fileId}\n");
```

### Returns

Returns `PNSendFileResult`.

#### PNSendFileResult

| Property Name | Type | Description |
| --- | --- | --- |
| `name` | string | Name of the uploaded file. |
| `fileId` | string | ID of the uploaded file. |

### Other examples

#### Send file with push notification

:::tip Trigger push notifications when sharing files
To send mobile push notifications when sharing a file, include `pn_apns` (for iOS) and/or `pn_fcm` (for Android) payloads in the `message` parameter of the `sendFile` method.
When PubNub detects these reserved keys, it automatically forwards the push notification to the appropriate push service (APNs or FCM) for all devices registered on the channel.
:::

```php
$message = [
  "text" => "Check out this file!",
  "pn_apns" => [
      "aps" => [
          "alert" => ["title" => "New File", "body" => "A file was shared"],
          "sound" => "default"
      ],
      "pn_push" => [
          [
              "targets" => [
                  [
                      "topic" => "com.yourapp.bundleid",
                      "environment" => "production"
                  ]
              ],
              "version" => "v2",
              "auth_method" => "token"
          ]
      ]
  ],
  "pn_fcm" => [
      "notification" => ["title" => "New File", "body" => "A file was shared"],
      "data" => [
          "type" => "file_shared",
          "channel" => "my-channel"
      ]
  ]
];

$result = $pubnub->sendFile()
  ->channel("my-channel")
  ->fileName("example.txt")
  ->message($message)
  ->fileHandle($fileHandle)
  ->sync();
```

For more details on push notification payload structure, see the [iOS Push](https://www.pubnub.com/docs/general/push/ios) and [Android Push](https://www.pubnub.com/docs/general/push/android) documentation. To prevent the sender from receiving their own push notification, add their device token to `excluded_devices` in the `pn_push` targets.

## List channel files

Retrieve a list of files uploaded to a `channel`.

### Method(s)

```php
$pubnub->listFiles()
    ->channel(string)
    ->sync();
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: stringDefault: n/a | Channel to get the list of files. |

### Sample code

```php
$channelFiles = $pubnub->listFiles()->channel($channelName)->sync();
$fileCount = $channelFiles->getCount();
if ($fileCount > 0) {
    print("There are {$fileCount} files in the channel {$channelName}\n");
    foreach ($channelFiles->getFiles() as $idx => $file) {
        print("File[{$idx}]: {$file->getName()} with ID: {$file->getId()},"
            . "size {$file->getSize()}, created at: {$file->getCreationTime()}\n");
    }
} else {
    print("There are no files in the channel {$channelName}\n");
}
```

### Returns

Returns `PNGetFilesResult`.

#### PNGetFilesResult

| Property Name | Type | Description |
| --- | --- | --- |
| `next` | string | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off. |
| `prev` | string | Random string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data. |
| `count` | Int | Number of files returned. |
| `data` | Array | Array of `PNGetFilesItem`. |

`PNGetFilesItem` contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `id` | string | `Id` of the uploaded file. |
| `name` | string | `Name` of the upload file. |
| `size` | string | `Size` of the uploaded file. |
| `creationTime` | string | Time of creation. |

## Get file URL

Generate a URL to download a file from the target `channel`.

### Method(s)

```php
$pubnub.getFileDownloadUrl()
    ->channel(string)
    ->fileId(string)
    ->fileName(string)
    ->sync()
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: string | Name of `channel` to which the file has been uploaded. |
| `fileName` *Type: string | Name under which the uploaded file is stored. |
| `fileId` *Type: string | Unique identifier for the file, assigned during upload. |

### Sample code

```php
$file = $channelFiles->getFiles()[0];

print("Getting download URL for the file...\n");
$downloadUrl = $pubnub->getFileDownloadUrl()
    ->channel($channelName)
    ->fileId($file->getId())
    ->fileName($file->getName())
    ->sync();

print("To download the file use the following URL: {$downloadUrl->getFileUrl()}\n");

print("Downloading file... ");
$downloadFile = $pubnub->downloadFile()
    ->channel($channelName)
    ->fileId($file->getId())
    ->fileName($file->getName())
    ->sync();
file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . $file->getName(), $downloadFile->getFileContent());
print("done. File saved as: {$file->getName()}\n");
```

### Returns

Returns `PNGetFileDownloadURLResult`.

#### PNGetFileDownloadURLResult

| Property Name | Type | Description |
| --- | --- | --- |
| `fileUrl` | string | `URL` to be used to download the requested file. |

## Download file

Download a file from the specified `channel`.

### Method(s)

```php
$pubnub.downloadFile()
    ->channel(string)
    ->fileId(string)
    ->fileName(string)
    ->sync()
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: string | Name of `channel` to which the file has been uploaded. |
| `fileName` *Type: string | Name under which the uploaded file is stored. |
| `fileId` *Type: string | Unique identifier for the file, assigned during upload. |

### Sample code

```php
$downloadFile = $pubnub->downloadFile()
    ->channel($channelName)
    ->fileId($file->getId())
    ->fileName($file->getName())
    ->sync();
file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . $file->getName(), $downloadFile->getFileContent());
```

### Returns

Returns `PNDownloadFileResult`.

#### PNDownloadFileResult

| Property Name | Type | Description |
| --- | --- | --- |
| `fileContent` | bytes | The file that was uploaded. |

## Delete file

Delete a file from the specified `channel`.

### Method(s)

```php
$pubnub.deleteFile()
    ->channel(string)
    ->fileId(string)
    ->fileName(string)
    ->sync()
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: string | The `channel` from which to delete the file. |
| `fileId` *Type: string | Unique identifier of the file to be deleted. |
| `fileName` *Type: string | Name of the file to be deleted. |

### Sample code

```php
$deleteFile = $pubnub->deleteFile()
    ->channel($channelName)
    ->fileId($file->getId())
    ->fileName($file->getName())
    ->sync();

if ($deleteFile->getStatus() === 200) {
    print("File deleted successfully\n");
} else {
    print("Failed to delete file\n");
}
```

### Returns

Returns `PNDeleteFileResult`.

| Property Name | Type | Description |
| --- | --- | --- |
| `status` | Int | Returns a status code. |

## Publish file message

Publish the uploaded file message to a specified channel.

This method is called internally by [sendFile](#send-file) as part of the file-sending process to publish the message with the file (already uploaded in a storage service) on a channel.

This message includes the file's unique identifier and name elements, which are needed to construct download links and inform channel subscribers that the file is available for download.

You can call this method when `sendFile` fails and returns the `status.operation === PNPublishFileMessageOperation` error. In that case, you can use the data from the `status` object to try again and use `publishFileMessage` to manually resend a file message to a channel without repeating the upload step.

### Method(s)

```php
$pubnub.publishFileMessage()
    ->channel(string)
    ->fileId(string)
    ->fileName(string)
    ->message(string|array)
    ->meta(string|array)
    ->shouldStore(Boolean)
    ->ttl(Int)
    ->customMessageType(string)
    ->sync();
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | Name of `channel` to publish file message. |
| `file_id` *Type: StringDefault: n/a | Unique identifier of the file. |
| `file_name` *Type: StringDefault: n/a | Name of the file. |
| `message`Type: DictionaryDefault: n/a | The payload. |
| `meta`Type: DictionaryDefault: n/a | Metadata object which can be used with the filtering ability. |
| `should_store`Type: BooleanDefault: `True` | Whether to store this message in history. Set to `False` to not store it. By default, messages are stored according to the retention policy set on your key. |
| `ttl`Type: IntDefault: `0` | How long the message should be stored in the channel's history. If not specified, defaults to the key set's retention value. |
| `customMessageType`Type: stringDefault: n/a | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes `-` and underscores `_` are allowed. The value cannot start with special characters or the string `pn_` or `pn-`. Examples: `text`, `action`, `poll`. |

### Sample code

```php
$publishFileMessageResult = $pubnub->publishFileMessage()
    ->channel($channelName)
    ->fileId($fileId)
    ->fileName($testFileName)
    ->message("Hello from PHP SDK")
    ->ttl(10)
    ->meta(["key" => "value"])
    ->customMessageType("custom")
    ->sync();
$timestamp = $publishFileMessageResult->getTimestamp();
print("File message published successfully: {$timestamp}\n");
```

### Returns

Returns `PNPublishFileMessageResult`.

#### PNPublishFileMessageResult

`PNPublishFileMessageResult` field:

| Property Name | Type | Description |
| --- | --- | --- |
| `timestamp` | string | The timetoken when the message was published. |