# PHP SDK for Sirv REST API

The official PHP SDK provides a simple, elegant interface for interacting with the [Sirv REST API](/help/rest-api/reference/). It handles authentication automatically and provides typed methods for all API operations.

Using an AI coding agent?

Install the [`sirv-api`](https://www.skills.sh/sirv/image-optimization-skill/sirv-api) skill, and your agent can call the Sirv API for you. Ask in plain words, such as “Upload the photos in /shoots/spring and tag them by product.” [See all 8 skills](/help/rest-api/sirv-skills-for-ai-agents/)

**Resources:**

-   [GitHub Repository](https://github.com/sirv/sirv-rest-api-php)
-   [Packagist](https://packagist.org/packages/sirv/sirv-rest-api-php)
-   [API Documentation](/help/rest-api/reference/)

## Installation

Install the SDK via Composer:

```bash
composer require sirv/sirv-rest-api-php
```

### Requirements

-   PHP 7.4 or higher
-   ext-json
-   ext-curl
-   Guzzle HTTP client 7.0+

## Quick Start

```php
<?php

require_once 'vendor/autoload.php';

use Sirv\SirvClient;

// Initialize the client
$client = new SirvClient(
    'your-client-id',
    'your-client-secret'
);

// Get account information
$account = $client->account()->get();
echo "Account: " . $account['alias'] . "\n";

// List files in a directory
$files = $client->files()->list('/');
foreach ($files['contents'] as $file) {
    echo $file['filename'] . "\n";
}
```

## Authentication

The SDK handles authentication automatically. When you make your first API call, it obtains an access token using your client credentials.

The token is automatically refreshed when it expires.

Tip

Get your API credentials from [Settings > API access](https://app.sirv.com/settings/api) in your Sirv account.

```php
$client = new SirvClient(
    'your-client-id',
    'your-client-secret'
);

// Optional: Manually authenticate to verify credentials
try {
    $token = $client->authenticate();
    echo "Authenticated successfully\n";
} catch (\Sirv\Exception\AuthenticationException $e) {
    echo "Authentication failed: " . $e->getMessage() . "\n";
}

// Optional: Request a token with custom expiry time (5-604800 seconds)
$token = $client->authenticate(3600); // Token valid for 1 hour
```

## Files API

Complete file management including upload, download, copy, rename, delete, and metadata operations.

### Available Methods

| Category | Methods |
| --- | --- |
| **File Operations** | `list()`, `getInfo()`, `upload()`, `download()`, `copy()`, `rename()`, `delete()`, `mkdir()`, `fetch()` |
| **Metadata** | `getMeta()`, `setMeta()`, `getApproval()`, `setApproval()`, `getTitle()`, `setTitle()`, `getDescription()`, `setDescription()`, `getProductMeta()`, `setProductMeta()`, `getTags()`, `setTags()`, `deleteTags()` |
| **Batch Operations** | `zip()`, `getZipResult()`, `deleteBatch()`, `getDeleteBatchResult()` |
| **Media & Export** | `spinToVideo()`, `videoToSpin()`, `exportToAmazon()`, `exportToWalmart()`, `exportToHomeDepot()`, `exportToLowes()`, `exportToGrainger()` |

### Basic Operations

```php
// List folder contents
$files = $client->files()->list('/images');

// Upload a file
$result = $client->files()->upload('/local/path/photo.jpg', '/images/photo.jpg');

// Download a file
$content = $client->files()->download('/images/photo.jpg');
file_put_contents('downloaded.jpg', $content);

// Copy a file
$client->files()->copy('/images/photo.jpg', '/backup/photo.jpg');

// Delete a file
$client->files()->delete('/images/photo.jpg');
```

### Search Files

```php
// Search files
$results = $client->files()->search([
    'query' => 'filename:*.jpg',
    'from' => '/images',
    'size' => 100
]);

// Paginate through results
if (isset($results['_scroll_id'])) {
    $nextPage = $client->files()->searchScroll($results['_scroll_id']);
}
```

### Metadata Operations

```php
// Set file metadata
$client->files()->setMeta('/images/photo.jpg', [
    'title' => 'My Photo',
    'description' => 'A beautiful sunset'
]);

// Set tags
$client->files()->setTags('/images/photo.jpg', ['nature', 'sunset', 'beach']);

// Set product metadata
$client->files()->setProductMeta('/images/product.jpg', [
    'id' => 'SKU123',
    'name' => 'Product Name',
    'brand' => 'Brand Name'
]);
```

### Batch Operations

```php
// Create ZIP file
$job = $client->files()->zip([
    '/images/photo1.jpg',
    '/images/photo2.jpg'
], 'my-archive.zip');

// Check ZIP status
$result = $client->files()->getZipResult($job['token']);
if ($result['status'] === 'completed') {
    echo "ZIP URL: " . $result['url'] . "\n";
}
```

## Account API

Manage your Sirv account settings and retrieve account information.

### Available Methods

| Method | Description |
| --- | --- |
| `get()` | Get account information including CDN URL and [account name](/help/getting-started/account-name-subdomain/) |
| `update(array $settings)` | Update account settings (minify, fetching) |
| `getLimits()` | Get API request limits and usage |
| `getStorage()` | Get storage usage information |
| `getUsers()` | List all account users |
| `getBillingPlan()` | Get billing plan details |
| `searchEvents(array $params)` | Search account events |
| `markEventsSeen(array $eventIds)` | Mark events as seen |

### Examples

```php
// Get account information
$account = $client->account()->get();

// Get API limits
$limits = $client->account()->getLimits();
echo "API calls used: " . $limits['used'] . "/" . $limits['limit'] . "\n";

// Get storage information
$storage = $client->account()->getStorage();
echo "Storage used: " . $storage['used'] . " bytes\n";

// Search account events
$events = $client->account()->searchEvents([
    'module' => 'files',
    'level' => 'error'
]);
```

## Statistics API

Retrieve usage statistics for your account.

| Method | Description |
| --- | --- |
| `getHttp($from, $to)` | Get HTTP transfer statistics |
| `getSpinViews($from, $to, $alias)` | Get spin viewer statistics (max 5 days) |
| `getStorage($from, $to)` | Get storage statistics |

```php
// HTTP transfer statistics
$httpStats = $client->stats()->getHttp('2024-01-01', '2024-01-31');

// Using DateTime objects
$from = new DateTime('2024-01-01');
$to = new DateTime('2024-01-31');
$httpStats = $client->stats()->getHttp($from, $to);

// Storage statistics
$storageStats = $client->stats()->getStorage('2024-01-01', '2024-01-31');
```

## User API

Retrieve user information.

```php
// Get current user info
$user = $client->user()->get();
echo "Email: " . $user['email'] . "\n";

// Get specific user info
$user = $client->user()->get('user-id-here');
```

## Error Handling

The SDK provides specific exception types for different error scenarios.

| Exception | Description |
| --- | --- |
| `AuthenticationException` | Invalid credentials or authentication failed |
| `ApiException` | General API errors |
| `RateLimitException` | Rate limit exceeded |
| `ValidationException` | Invalid request parameters |

```php
use Sirv\SirvClient;
use Sirv\Exception\AuthenticationException;
use Sirv\Exception\ApiException;
use Sirv\Exception\RateLimitException;

try {
    $client = new SirvClient('client-id', 'client-secret');
    $files = $client->files()->list('/');
} catch (AuthenticationException $e) {
    echo "Auth error: " . $e->getMessage() . "\n";
} catch (RateLimitException $e) {
    echo "Rate limited. Retry after: " . $e->getRetryAfter() . " seconds\n";
} catch (ApiException $e) {
    echo "API error: " . $e->getMessage() . "\n";
    echo "HTTP Status: " . $e->getHttpStatusCode() . "\n";
}
```

### RateLimitException Methods

-   `getRetryAfter()` - Seconds to wait before retrying
-   `getRateLimit()` - Rate limit for the endpoint
-   `getRateLimitRemaining()` - Remaining requests in window

### ApiException Methods

-   `getHttpStatusCode()` - HTTP status code
-   `getRequestId()` - Request ID for debugging
-   `getErrorDetails()` - Additional error details

## Configuration

### Timeout

```php
// Set custom timeout (in seconds)
$client = new SirvClient('client-id', 'client-secret', 60);
```

### Custom Guzzle Options

```php
// Pass additional Guzzle HTTP client options
$client = new SirvClient('client-id', 'client-secret', 30, [
    'proxy' => 'http://proxy.example.com:8080',
    'verify' => false
]);
```

Only turn off SSL verification for testing, and keep it on in production.
