Type to search...

Detailed documentation


Configuring your client will give you access to use the Shardimage API. Depending on the way of usage, there are different ways to set up the client config. You can use:

  • apiKey with apiSecret to use the Shardimage API and host images without secure settings
  • apiKey with imageSecret to only host images with advanced URL security
  • The two above options together will grant you a multipurpose client
  • accessToken for uploading images with using the accessToken features and host images without secure settings
  • accessToken with apiAccessTokenSecret for featured uploading and image hosting

You can find or create the apiKey, apiSecret and imageSecret on the Shardimage site.

The accessToken can be generated only through the Shardimage API with an already configured client. For more information, check the related articles:

Multi purpose configuration

$client = new Client([       //we will use this configured $client for the further examples
    'apiKey' => '<apiKey>',
    'apiSecret' => '<apiSecret>',
    'imageSecret' => '<imageSecret>',
    'cloudId' => '<cloudId>',

Manage Access tokens

Access tokens are tools for image uploading and image hosting with additional benefits. It can be limited in time and by usage count and there are many extra features. After creating it you can set it up in the configuration.


use shardimage\shardimagephp\models\accesstoken\ImageUrlAccessToken;
use shardimage\shardimagephp\models\accesstoken\ImageUrlAccessTokenExtra;
use shardimage\shardimagephp\models\accesstoken\ImageUrlAccessTokenExtraAuthentication;
$authentication = new ImageUrlAccessTokenExtraAuthentication();
$authentication->setAuthenticationData('<username1>', '<password1>');
$authentication->setAuthenticationData('<username2>', '<password2>');
$token = new ImageUrlAccessToken();
$token->expiry = time() + 3600; //alive for 1 hour
$token->limit = 1000; //alive for 1000 requests
$token->extra = new ImageUrlAccessTokenExtra([
    'cloudId' => '<cloudId>',
    'secret' => 'teqStwAvPi',
    'authentication' => $authentication,
$response = $this->client->getAccessTokenService()->create($token);

Access token extras

Image URL Authentication

Set basic HTTP Authentication to the generated image URL.

use shardimage\shardimagephp\models\accesstoken\MixedShaPasswordHash;
use shardimage\shardimagephp\models\accesstoken\ImageUrlAccessTokenExtraAuthentication;
$authentication = new ImageUrlAccessTokenExtraAuthentication();
$authentication->setAuthenticationData('<username1>', '<password1>');
// or use password object which uses encryption on the password
$authentication->setAuthenticationData('<username2>', new MixedShaPasswordHash('<password2>'));

Notification URLs

Useful feature to create callbacks for successful API requests. More information »

use shardimage\shardimagephp\models\accesstoken\UploadAccessToken;
use shardimage\shardimagephp\models\accesstoken\UploadAccessTokenExtra;
$token = new UploadAccessToken();
$token->expiry = time() + 3600; //alive for 1 hour
$token->limit = 1000; //alive for 1000 requests
$token->extra = new UploadAccessTokenExtra([
    //'cloudId' => 'tQTTQ81u',   // limited to one cloud
    'notificationUrls' => [
$response = $client->getAccessTokenService()->create($token);
if ($response instanceof UploadAccessToken) {
    $tokenId = $response->id;

Manage Billing

Through the Shardimage API it’s possible to follow the billing details like used storage, network or cu (compute unit). It requires the client configured with the apiKey and apiSecret.

With the shardimage\shardimagephp\models\billing\DetailParams class, the API query can be easily configured.

use shardimage\shardimagephp\models\billing\Detail;
use shardimage\shardimagephp\models\billing\DetailParams;
$detailParams = new DetailParams();
$detailParams->dateFrom = strtotime('2018-10-01');
$detailParams->dateTo = strtotime('2018-10-10');
$detailParams->datePartition = DetailParams::DATE_PARTITION_DAY;
$detailParams->group = DetailParams::GROUP_CU;
$result = $client->getBillingService()->detail([], $detailParams);
if ($result instanceof Detail) {

Manage Clouds

In the Shardimage system you can upload and store your images in clouds. Clouds can be created and managed on the Shardimage site directly or through API.


use shardimage\shardimagephp\models\cloud\IndexParams;
$indexParams = new IndexParams();
$indexParams->maxResults = 10;   //10 rows per page
$indexParams->nextPageToken = 1; //First page
$indexParams->projection = [     //projections to manipulate the query result
$indexParams->order = '-name';   // ORDER BY `name` DESC
$clouds = $client->getCloudService()->index([], $indexParams);


use shardimage\shardimagephp\models\cloud\Cloud;
//let's use the provided Cloud class
$cloud = new Cloud();
$cloud->name = 'ExampleCloud';
$cloud->description = 'Stores my example website\'s images.';
$cloud->settings = [
    'cdnCacheHeaderTtl' => [
        'status' => true,
        'ttl' => 12345,
$cloud = $client->getCloudService()->create($cloud);
$cloudId = '';
if ($cloud instanceof Cloud) {
    $cloudId = $cloud->id;


$cloud = $client->getCloudService()->view($cloudId);     //find the cloud by it's ID
if ($cloud instanceof Cloud) {                           //cloud exists and found
    $cloud->settings['deliverySecureUrl'] = [            //let's add security to the cloud images
        'status' => true
    $cloud = $client->getCloudService()->update($cloud);  //and update it

Uploading images

Upload local images:

Single thread:

$file = __DIR__ . '/' . $file;
$fileName = 'Example';
$result = $client->getUploadService()->upload([
    'file' => $file,
    'cloudId' => '<cloudId>',
    'publicId' => $fileName,
], [    //optional parameters
    'tags' => [

Multiple thread

$files = [
$client->defer(true); //turning on
foreach ($files as $file) {
        'file' => $file,
    ], [
        'tags' => [
$result = $client->defer(false); //without turning off, nothing will happen

Upload remote images

$params = [
    'resource' => 'https://upload.wikimedia.org/wikipedia/en/6/6b/Yii-logo-transparent.png',
    'publicId' => 'Yii2logo',
$optParams = [
    'tags' => [
$client->getUploadService()->uploadRemote($params, $optParams);

Using UploadBuilder

Using the builder class can make uploading easier by giving a developer friendly usage to build up upload parameters.

use shardimage\shardimagephp\builders\UploadBuilder;
$builder = (new UploadBuilder())
$result = $client->getUploadService()->upload($builder->build());

Manage Firewalls

Firewalls are rule collections. If you create and add one to a cloud, it can limit the accessibility of the cloud’s images.

For further information about setting up the firewall rules, please read our article here »

use shardimage\shardimagephp\models\firewall\Firewall;
use shardimage\shardimagephp\models\firewall\Rules;
use shardimage\shardimagephp\data\Country;
$firewall = new Firewall();
$rules = new Rules();
$firewall->name = "First firewall";
$rules->blockIfNotMatchAllow = true;
$rules->countryAccept = [Country::UNITED_STATES_OF_AMERICA];
$firewall->rules = $rules;
$firewall->cloudIds = ['<cloudId>', ...];   //you can add the firewall to the given cloud during the creation also

Manage Super Backups

Super backup is a Shardimage feature which provides you safety backup for your images. You only need to decide which storage provider you want to use, then add the connection datas and permissions to start backing up the files. For default, only the newly uploaded images will be backed up. If you want to do it for your already uploaded images, you will need to update your super backup and set up a new task. For managing your super backups, we recommend to use the SuperBackupService class which we provide.

Setting up backup target

use shardimage\shardimagephp\models\cloud\Cloud;
use shardimage\shardimagephp\models\superbackup\SuperBackup;
use shardimage\shardimagephp\models\superbackup\targets\CloudinaryTarget;
$target = new CloudinaryTarget();
$target->cloudName = '<cloudinaryCloudName>';
$target->apiKey = '<cloudinaryApiKey>';
$target->apiSecret = '<cloudinaryApiSecret>';
$backup = new SuperBackup();
$backup->cloud = new Cloud();
$backup->cloud->id = 'cloudId';      //cloud to backup it's images
$backup->target = $target;
$backup->copyDelay = 0;
$backup->deleteDelay = null;         //only copy, never delete
$result = $client->getSuperBackupService()->create($backup);

Manage task

There are two kind of task, that you can set up:

  • forceCopyAll will copy all of your images from your cloud, even it’s already backed up
  • scanAgainAndCopy will copy only the missing images to the backup provider

If you want to create a backup to your cloud, which has already uploaded images, it’s a good practice to create the backup, and then update it, with the scanAgainAndCopy task.

use shardimage\shardimagephp\models\superbackup\targets\CloudinaryTarget;
use shardimage\shardimagephp\models\superbackup\Task;
$backup = $client->getSuperBackupService()->view('cloudId');   //The cloud ID identifies the backup as well
$backup->target->apiSecret = 'cloudinaryApiSecret';    //apiSecret won't be passed in response, it must to be given again
$task = new Task();
$task->type = Task::TASK_...;
$backup->task = $task;
$response = $client->getSuperBackupService()->update($backup);

Super Backup Logs

If you turn on logging for your super backup, you can list the log entries through API.

use shardimage\shardimagephp\models\superbackuplog\IndexParams;
$indexParams = new IndexParams();
$indexParams->filters = [
$backupLogList = $client->getSuperBackupLogService()->index(['cloudId' => '<cloudId>'], $indexParams);

Manage Images

By using ImageService, you can:

Manage Jobs

Jobs are background processes in the Shardimage system. If a task has big resource requirement, it will create a job the system will solve it optimized. For example deleting images creates a new job.

Jobs can be:

Creating URLs

You can create URLs to the uploaded images with the UrlService class. This function works completely without the Shardimage API, so there are no request costs. Please keep in my, you will need the exact data to generate the URLs properly, there are no prevalidations.

$params = [
    'cloudId' => 'cloudId';
    'publicId' => 'publicId';
$optParams = [                 //optional
    'option' => null,          //options defined by shardimage\shardimagephp\factories\Option
    'transformation' => null,  //defined by shardimage\shardimagephp\factories\Transformation
    'version' => null,         //version number (to force cache miss)
    'format' => null,          //output format
    'seo' => null,             //SEO filename
    'security' => null,        //basic or token
    'default_public_id' => '<default_public_id>', //default public ID
$url = $client->getUrlService()->create($params, $optParams);


With options, it’s possible to add or alter URL functions. For further information, please read our official documentation about Shardimage URL Options »

use shardimage\shardimagephp\factories\Option;
$option = new Option();
$option->urlExpire(time() + 3600); //generated url only available for 1 hour
$option->download();               //opening the URL will automatically download the image
$url = $client->getUrlService()->create($params, ['option' => $option]);
echo $url; // https://img.shardimage.com/<cloudId>/o-url-exp:1539347967_download/i/<publicId>


Image transformation is one of the major service of the Shardimage. Because the Shardimage system stores the originally uploaded images and execute the transformation in runtime. It’s a good practice to secure the URL with basic or token security to avoid malicious usage.

use shardimage\shardimagephp\factories\Transformation;
$tr = new Transformation();
$tr->size(500);  //500 width and heigth
$tr->blur(100);  //blur effect
$url = $client->getUrlService()->create($params, ['transformation' => $tr]);
echo $url; // https://img.shardimage.com/<cloudId>/wh:500_e:blur:100/i/<publicId>


If the cloud has the Force Secure Url setting turned on, then the images in it can be reached only through secured URL. All valid URL parameters will be hashed in the security string, so it won’t be possible to modify any parameters in the generated URL. This will provide safety for your images against malicious usage like requesting expensive transformations over and over again.


This security is available if apiKey and imageSecret is configured in client.

$url = $client->getUrlService()->create($params, ['secure' => 'basic']);


Token security requires the accessToken and accessTokenSecret to be configured in client.

$url = $client->getUrlService()->create($params, ['secure' => 'token']);


With Transformation and Text factory, you can place text layer on the image.

use shardimage\shardimagephp\factories\Text;
use shardimage\shardimagephp\factories\Transformation;
$firstText = (Text::create("My first\ntext layer"))->googleFonts("Montserrat")->size(40)->lineSpace(20);
$secondText = (Text::create("My second text layer"))->googleFonts("Pacifico")->size(30);
$tr = (new Transformation())->group()->gLeft()->color('fffa')->textOverlay($firstText)
$url = $client->getUrlService()->create($params, ['transformation' => $tr]);
echo $url;

Handle errors

Single tasks

In case of single task, errors are passed through exceptions, so it’s a good practice to put the code into try-catch block. For fast response, the $client->getLastError() contains the last error’s message, otherwise it’s up to the developer to process the exception. If exception handling is unwanted, it can be turned off in the Client by setting false the softExceptionEnabled property. This case, Response object will return in case of error.

$file = __DIR__ . '/' . $file;
try {
    $result = $client->getUploadService()->upload([
        'file' => $file,
        'cloudId' => '<cloudId>',
    ], [    //optional parameters
        'publicId' => 'already-used-public-id',
        'tags' => [
} catch (\Exception $ex) {
    return 'Upload error: ' . $ex->getMessage(); //API error / publicId: Public ID already exists!

Multiple tasks

Multiple thread tasks will not throw exception in case of error. The returned result will be an array with failed Response objects and/or successfully executed task results. Take our previous bulk upload example:

$files = [
$result = $client->defer(false);
foreach ($result as $_result) {
    if ($_result instanceof Response) {     // if any error occured
        $error = $_result->error;           // ResponseError object
        throw new $error->exception;        // throwing the occured exception

Special case: Rate limitation

Please check out our guide about rate limitation here »

Other topics

Iterating index result

Using IndexIterator class makes listing more easy.

$indexParams = new \shardimage\shardimagephp\models\image\IndexParams(['maxResults' => 10]);
$iterator = $client->getImageService()->indexIterator()->withParams(['cloudId' => '<cloudId>'])->withIndexParams($indexParams); // parameters are based on normal listing
$func = function ($ex, $iterator) {    // optional
    // code
$iterator = $iterator->withRateLimitTrap($func); // catching TooManyRequestsHttpException exception and run the given callable code
foreach ($iterator as $model) {
    // $model is the iterated object, since we used `getImageService` to construct our iterator, it's an image object.
    if ($model instanceof Image) {
        echo $iterator->key() . " -> $model->publicId\n";
Table of contents