# REST API PHP Examples

The [Sirv REST API](/help/rest-api/reference/) can be used to perform more than 60 commands on your Sirv account.

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/)

You can either write your own PHP scripts or use the Sirv PHP class below.

## PHP Class

The Sirv team has written a PHP class with 10 of the most popular API commands. Each command is described below. In all cases, first you must connect to the API.

Visit GitHub for the latest version of the PHP Class: [https://github.com/sirv/sirv-rest-api-php/](https://github.com/sirv/sirv-rest-api-php/)

### Connect to Sirv with PHP

1.  [Create an API client](https://app.sirv.com/settings/api) in your Sirv account. You’ll receive a client ID and client Secret.
    
2.  Add the Sirv PHP Class package:
    

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

3.  Keep your client ID and secret in the SIRV\_CLIENT\_ID and SIRV\_CLIENT\_SECRET environment variables, not in the code. Initialize the class with them to get a token:

```php
    $sirv = new SirvAPIClient(
    getenv('SIRV_CLIENT_ID'),
    getenv('SIRV_CLIENT_SECRET'),
    '',
    '',
    'Sirv PHP client'
    );

    // Check if client has successfully connected:
    echo 'Is connected: '.$sirv->isConnected();
    echo '<br>';

    // Get token and its expiry time
    $token = $sirv->getToken();
    $tokenExpireTime = $sirv->getTokenExpireTime();

    echo 'Token: '.$token;
    echo '<br>';
    echo 'Token expire time: '.$tokenExpireTime;
```

4.  If you already have a valid token, skip step 3. Keep the token in SIRV\_TOKEN and its expiry time in SIRV\_TOKEN\_EXPIRES, and use this instead:

```php
    $token = getenv('SIRV_TOKEN');
    $tokenExpireTime = getenv('SIRV_TOKEN_EXPIRES');

    $sirv = new SirvAPIClient(
      getenv('SIRV_CLIENT_ID'),
      getenv('SIRV_CLIENT_SECRET'),
      $token,
      $tokenExpireTime,
      'Sirv PHP client'
    );
```

Now you can perform more than 60 [Sirv REST API methods](/help/rest-api/reference/).

### Upload file

Upload a local file to Sirv your Sirv account:

```php
$sirv->uploadFile('example/local-file.jpg', 'example-folder/file-on-sirv.jpg');
```

A successful upload will return the following response headers in JSON format. There is no body. A response code of 200 means success:

```html
HTTP/2 200
date: Sat, 02 May 2020 16:57:19 GMT
content-length: 0
x-ratelimit-limit: 2000
x-ratelimit-remaining: 1992
x-ratelimit-reset: 1588441712
x-ratelimit-type: rest:post:files:upload
access-control-allow-origin: *
access-control-expose-headers: *
cache-control: no-cache
server: Sirv.API
strict-transport-security: max-age=31536000
```

To upload many files, use $sirv->uploadFile in a loop:

```php
$images = array(
  array('example/local-file-1.jpg', 'example-folder/file-on-sirv-1.jpg'),
  array('example/local-file-2.jpg', 'example-folder/file-on-sirv-2.jpg'),
  array('example/local-file-3.jpg', 'example-folder/file-on-sirv-3.jpg'),
  array('example/local-file-4.jpg', 'example-folder/file-on-sirv-4.jpg'),
  ...
);
foreach($images as $image) {
  $sirv->uploadFile($image[0], $image[1]);
}
```

### Convert video to spin

```php
$client = new http\Client;
$request = new http\Client\Request;

$body = new http\Message\Body;
$body->append('{
 "filename": "/path/to/video/Example.mp4"
}');

$request->setRequestUrl('https://api.sirv.com/v2/files/video2spin');
$request->setRequestMethod('POST');
$request->setBody($body);

$request->setHeaders(array(
 'authorization' => 'Bearer ' . getenv('SIRV_TOKEN'),
 'content-type' => 'application/json'
));

$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();
```

### Fetch image from URL

-   Endpoint: `https://api.sirv.com/v2/files/fetch`
-   Documentation: [Fetch URL](/help/rest-api/reference/upload-download/fetch-url/)

Fetch remote images via URL and save them to your Sirv account:

```php
$images = array(
  array(
    'url' => 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c0/Castle_Mountain.jpg/800px-Castle_Mountain.jpg',
    'filename' => '/Folder-on-Sirv/file-1.jpg',
    'wait' => true
  ),
  array(
    'url' => 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c0/Castle_Mountain.jpg/800px-Castle_Mountain.jpg',
    'filename' => '/Folder-on-Sirv/file-2.jpg',
    'wait' => true
  ),
);
$sirv->fetchImage($images);
```

### Get folder contents

-   Endpoint: `https://api.sirv.com/v2/files/readdir`
-   Documentation: [Read folder contents](/help/rest-api/reference/files/read-folder/)

Fetch a list of folder contents:

```php
$contents = $sirv->getFolderContents('ExampleFolder');
print_r($contents);
```

### Delete file / folder

To delete a folder, it must be empty.

-   Endpoint: `https://api.sirv.com/v2/files/delete`
-   Documentation: [Delete file or empty folder](/help/rest-api/reference/files/copy-rename-delete/#delete-file-or-empty-folder)

```php
$sirv->deleteFile('ExampleFolder/file.jpg');
```

### Get file info

-   Endpoint: `https://api.sirv.com/v2/files/stat`
-   Documentation: [Get file info](/help/rest-api/reference/files/file-info/)

```php
$info = $sirv->getFileStat('ExampleFolder/file-on-sirv.jpg');
```

### Folder options

-   Endpoint: `https://api.sirv.com/v2/files/options`
-   Documentation: [Get folder options](/help/rest-api/reference/folder-settings/folder-options/#get-folder-options)

Get folder options:

```php
$f_options = $sirv->getFolderOptions('ExampleFolder');
```

Set folder options:

```php
$f_options = array(
  'scanSpins' => false,
  'nameSpinsAfterFolder' => true,
  'allowListing' => false
);
$sirv->setFolderOptions('folderName', $f_options);
```

### Get account info

-   Endpoint: `https://api.sirv.com/v2/account`
-   Documentation: [Get account info](/help/rest-api/reference/account/account-info/#get-account-info)

```php
$info = $sirv->getAccountInfo();
```

### Get usage info

```php
$info = $sirv->getStorageInfo();
```

### Configure CDN

```php
$sirv->configCDN(
  true, // true - activate CDN, false - disable
  'account-name-here'
);
```

Once the CDN is active, your files are served from Sirv’s global CDN.
