> ## Documentation Index
> Fetch the complete documentation index at: https://docs.convertly.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# PHP SDK

> Use the official Convertly PHP SDK for server-side media conversion, compression, tools, batch jobs, and WordPress integrations.

The Convertly PHP SDK is a small cURL-based client for server-side apps and WordPress plugins. It has zero dependencies beyond the PHP cURL extension.

<Note>
  **CDN delivery** is separate from this API client. To serve optimized images from the CDN, use a [delivery namespace](/docs/image-cdn/operations) and either [Convertly Storage](/docs/files-and-storage) file ids/slugs or an [origin source](/docs/image-cdn/operations#origin-sources) for your deployed asset URLs. See [Image CDN setup](/guides/image-cdn-setup).
</Note>

```bash theme={"system"}
composer require convertly/convertly-php
```

## Create a client

```php theme={"system"}
<?php

require __DIR__ . '/vendor/autoload.php';

use Convertly\ConvertlyClient;

$convertly = new ConvertlyClient(getenv('CONVERTLY_API_KEY'));
```

For a custom API origin (for example staging):

```php theme={"system"}
$convertly = new ConvertlyClient(
    getenv('CONVERTLY_API_KEY'),
    'https://staging.convertly.sh'
);
```

## Convert a file

```php theme={"system"}
$result = $convertly->convertFile(__DIR__ . '/photo.png', 'webp', [
    'compression' => 'balanced',
    'resizeWidth' => 1600,
    'saveToStorage' => false,
]);

if (!$result['ok']) {
    throw new RuntimeException($result['error']);
}

$outputUrl = $result['body']['url'];
```

### Conversion options

| Option          | Type     | Description                                                |
| --------------- | -------- | ---------------------------------------------------------- |
| `compression`   | `string` | Image compression preset: `high`, `balanced`, `ultra`.     |
| `resize`        | `string` | Resize strategy: `fit`, `fill`, `cover`, `contain`.        |
| `resizeWidth`   | `int`    | Target width in pixels.                                    |
| `resizeHeight`  | `int`    | Target height in pixels.                                   |
| `autoOrient`    | `bool`   | Auto-rotate based on EXIF. Default `true`.                 |
| `mono`          | `bool`   | For SVG tracing: `true` for monochrome, `false` for color. |
| `saveToStorage` | `bool`   | Save the output to Convertly Storage.                      |

For raster-to-SVG conversion, color is preserved by default. Pass `'mono' => true` only when you want monochrome tracing.

## Compress a file

```php theme={"system"}
$result = $convertly->compressFile(__DIR__ . '/hero.jpg', [
    'quality' => 82,
    'stripMetadata' => true,
    'mode' => 'quality',
]);
```

### Compression options

| Option          | Type     | Description                                 |
| --------------- | -------- | ------------------------------------------- |
| `mode`          | `string` | `quality` (1-100) or `target-size` (bytes). |
| `quality`       | `int`    | 1-100 quality level when mode is `quality`. |
| `stripMetadata` | `bool`   | Remove EXIF and metadata.                   |
| `saveToStorage` | `bool`   | Save the output to Convertly Storage.       |

## Media tools

Use the generic `mediaTool()` method for any Convertly media tool endpoint:

```php theme={"system"}
// Background removal
$result = $convertly->mediaTool('remove-background', __DIR__ . '/product.jpg', [
    'format' => 'png',
    'model' => 'medium',
]);

// Thumbnail from video
$result = $convertly->mediaTool('thumbnail', __DIR__ . '/video.mp4', [
    'time' => 5.0,
    'width' => 320,
    'height' => 180,
]);

// Watermark
$result = $convertly->mediaTool('watermark', __DIR__ . '/photo.jpg', [
    'text' => 'Convertly',
    'position' => 'bottom-right',
    'opacity' => 0.5,
]);

// PDF preview
$result = $convertly->mediaTool('pdf-preview', __DIR__ . '/document.pdf', [
    'page' => 1,
    'width' => 800,
]);

// Image to PDF
$result = $convertly->mediaTool('image-to-pdf', __DIR__ . '/scan.png');

// Strip metadata
$result = $convertly->mediaTool('strip-metadata', __DIR__ . '/photo.jpg');

// Inspect file
$result = $convertly->mediaTool('inspect', __DIR__ . '/video.mp4');
```

Available tool slugs: `thumbnail`, `pdf-preview`, `image-to-pdf`, `strip-metadata`, `poster-frame`, `extract-audio`, `watermark`, `inspect`, `trim`, `gif`, `storyboard`, `transform`, `remove-background`.

Pass `'async' => 'true'` in `$fields` for longer media-tool work. Async tool responses include a `jobId`; use `getJob($jobId)` to poll completion.

## Convertly Storage

The WordPress-bundled SDK also exposes storage helpers used by the plugin:

```php theme={"system"}
// List root folders and root files
$folders = $convertly->getFolders('');
$files = $convertly->getFiles('', 100, 0);

// List a nested folder
$folders = $convertly->getFolders($parentFolderId);
$files = $convertly->getFiles($parentFolderId, 100, 0);

// Upload a local file into a Convertly folder
$uploaded = $convertly->uploadFile(__DIR__ . '/hero.jpg', $parentFolderId);
```

Use an empty string (`''`) for root-level storage listings. Use `null` only when you intentionally want the API default behavior.

## Batch jobs

Upload multiple files in a single batch job:

```php theme={"system"}
$result = $convertly->createJob(
    [
        __DIR__ . '/photo1.png',
        __DIR__ . '/photo2.png',
        __DIR__ . '/photo3.png',
    ],
    [
        'format' => 'webp',
        'compression' => 'balanced',
        'resizeWidth' => 1600,
    ]
);

$jobId = $result['body']['jobId'];
```

## Job management

```php theme={"system"}
// Get a job by ID
$job = $convertly->getJob($jobId);

// List recent jobs
$jobs = $convertly->getJobs(20);

// Check status
if ($job['body']['status'] === 'completed') {
    $outputUrl = $job['body']['result']['url'];
}
```

## Error handling

Every method returns a consistent response array:

```php theme={"system"}
$result = $convertly->convertFile(__DIR__ . '/photo.png', 'webp');

if (!$result['ok']) {
    $status = $result['status'] ?? 0;
    $error = $result['error'] ?? 'Unknown error';
    // Handle error
}
```

Common error cases:

* Missing API key: `['ok' => false, 'error' => 'Missing Convertly API key.']`
* Missing cURL extension: `['ok' => false, 'error' => 'Convertly uploads require the PHP cURL extension.']`
* Unreadable file: `['ok' => false, 'error' => 'File is not readable.']`
* HTTP errors: `['ok' => false, 'status' => 429, 'error' => 'Rate limit exceeded.']`

## WordPress integration

The WordPress plugin is built on this SDK, so plugin behavior and standalone PHP behavior stay aligned. You can use the same `ConvertlyClient` class in custom WordPress themes or plugins:

```php theme={"system"}
$convertly = new ConvertlyClient(get_option('convertly_api_key'));
$result = $convertly->convertFile($upload_path, 'webp', [
    'compression' => get_option('convertly_compression', 'balanced'),
    'saveToStorage' => true,
]);
```

## Method reference

| Method                                              | Description                                                      |
| --------------------------------------------------- | ---------------------------------------------------------------- |
| `new ConvertlyClient($apiKey, $baseUrl?)`           | Create a client. Default base URL is `https://convertly.sh`.     |
| `hasApiKey()`                                       | Check if an API key was provided.                                |
| `convertFile($path, $format, $options?)`            | Convert a file to another format.                                |
| `compressFile($path, $options?)`                    | Compress an image or document.                                   |
| `mediaTool($tool, $path, $fields?)`                 | Call any media tool endpoint.                                    |
| `createJob($paths, $fields)`                        | Create a batch job with multiple files.                          |
| `getJob($jobId)`                                    | Get a job by ID.                                                 |
| `getJobs($limit?)`                                  | List recent jobs. Default limit is 20.                           |
| `getFiles($folderId?, $limit?, $offset?, $search?)` | List Convertly Storage files. Empty string lists root files.     |
| `getFolders($parentId?, $search?)`                  | List Convertly Storage folders. Empty string lists root folders. |
| `uploadFile($path, $folderId?)`                     | Upload a local file into Convertly Storage.                      |
