Skip to content

PHP SDK for Sirv REST API

By , Head of Sirv StudioUpdated

Open this page in a new chat

Short answer

Sirv's official PHP SDK wraps the Sirv REST API, so you can upload, download, search and manage files, metadata, users and account statistics from your code. Install it with composer require sirv/sirv-rest-api-php, then connect with the client ID and secret from your Sirv account's API settings. The SDK gets and refreshes the access token for you.

After reading this you will know

  • How to install the SDK and connect to your Sirv account
  • Which file, account, statistics and spin methods it offers
  • How to handle errors and limits

The official PHP SDK provides a simple, elegant interface for interacting with the Sirv REST API. It handles authentication automatically and provides typed methods for all API operations.

Resources:

Install the SDK via Composer:

composer require sirv/sirv-rest-api-php
  • PHP 7.4 or higher
  • ext-json
  • ext-curl
  • Guzzle HTTP client 7.0+
<?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";
}

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.

$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

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

CategoryMethods
File Operationslist(), getInfo(), upload(), download(), copy(), rename(), delete(), mkdir(), fetch()
MetadatagetMeta(), setMeta(), getApproval(), setApproval(), getTitle(), setTitle(), getDescription(), setDescription(), getProductMeta(), setProductMeta(), getTags(), setTags(), deleteTags()
Batch Operationszip(), getZipResult(), deleteBatch(), getDeleteBatchResult()
Media & ExportspinToVideo(), videoToSpin(), exportToAmazon(), exportToWalmart(), exportToHomeDepot(), exportToLowes(), exportToGrainger()
// 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
$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']);
}
// 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'
]);
// 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";
}

Manage your Sirv account settings and retrieve account information.

MethodDescription
get()Get account information including CDN URL and account name
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
// 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'
]);

Retrieve usage statistics for your account.

MethodDescription
getHttp($from, $to)Get HTTP transfer statistics
getSpinViews($from, $to, $alias)Get spin viewer statistics (max 5 days)
getStorage($from, $to)Get storage statistics
// 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');

Retrieve user information.

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

The SDK provides specific exception types for different error scenarios.

ExceptionDescription
AuthenticationExceptionInvalid credentials or authentication failed
ApiExceptionGeneral API errors
RateLimitExceptionRate limit exceeded
ValidationExceptionInvalid request parameters
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";
}
  • getRetryAfter() - Seconds to wait before retrying
  • getRateLimit() - Rate limit for the endpoint
  • getRateLimitRemaining() - Remaining requests in window
  • getHttpStatusCode() - HTTP status code
  • getRequestId() - Request ID for debugging
  • getErrorDetails() - Additional error details
// Set custom timeout (in seconds)
$client = new SirvClient('client-id', 'client-secret', 60);
// 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.

Back to top