PHP
Real-time image resizing, automatic optimization, and file uploading in PHP using ImageKit.io.
​ImageKit's PHP SDK provides comprehensive yet straightforward asset upload, transformation, optimization, and delivery capabilities that you can implement seamlessly in your existing PHP application.
This is a quick start guide to show you how to integrate ImageKit in your PHP application. The code samples covered here are hosted on Github - https://github.com/imagekit-developer/imagekit-php/tree/master/sample​.​
This guide walks you through the following topics:

Setting up ImageKit PHP SDK

Prerequisites

To use ImageKit PHP SDK, you must be using PHP version 5.6.0 or later with JSON PHP Extension and cURL PHP Extension enabled.

Create a new Project

Let's create a dummy project called sample using composer in a folder.
1
composer init --name imagekit/sample --type project
Copied!
It will prompt a few options. Select defaults by pressing enter.

Install imagekit/imagekit using Composer

1
composer require imagekit/imagekit
Copied!

Initialize SDK

1
// Import autoloader from vendor
2
// If not using PSR-4 is not configured in composer.json file for your project
3
require_once __DIR__ . '/vendor/autoload.php';
4
​
5
use ImageKit\ImageKit;
6
​
7
// For demonstration purposes, the documentation would use https://ik.imagekit.io/demo as urlEndpoint
8
$imageKit = new ImageKit(
9
"{publicKey}",
10
"{publicKey}",
11
"{urlEndpoint}"
12
);
13
​
Copied!
    urlEndpoint is the required parameter. You can get the value of URL-endpoint from your ImageKit dashboard - https://imagekit.io/dashboard#url-endpoints.
    publicKey and privateKey parameters are also required as these would be used for all ImageKit API, server-side upload, and generating token for client-side file upload. You can get these parameters from the developer section in your ImageKit dashboard - https://imagekit.io/dashboard#developers.

Generating url for rendering images

URL for image with relative path

1
$imageURL = $imageKit->url(['path' => '/default-image.jpg']);
2
​
3
echo('Url : ' . $imageURL);
4
// https://ik.imagekit.io/demo/default-image.jpg
Copied!

URL for image with relative path and custom URL-endpoint

1
$imageURL = $imageKit->url([
2
'urlEndpoint' => 'https://ik.imagekit.io/test',
3
'path' => '/default-image.jpg',
4
]);
5
​
6
echo('Url : ' . $imageURL);
7
// https://ik.imagekit.io/test/default-image.jpg
Copied!

URL for image with absolute url

If you have an absolute image path coming from the backend API e.g. https://www.custom-domain.com/default-image.jpg then you can use src prop to load the image.
1
$imageURL = $imageKit->url([
2
'src' => 'https://example.com/default-image.jpg'
3
]);
4
​
5
echo('Url : ' . $imageURL);
6
// https://ik.imagekit.io/demo/default-image.jpg
Copied!

Applying common image manipulations

This section covers the basics:
The PHP SDK gives a name to each transformation parameter e.g. height for h and width for w parameter. It makes your code more readable. See the full list of supported transformations in PHP SDK on Github.
πŸ‘‰ If the property does not match any of the available options, it is added as it is. πŸ‘‰ Note that you can also use h and w parameter instead of height and width. See the complete list of transformations supported in ImageKit here.

Resizing images in PHP

Let's resize the image to width 400 and height 300.
1
$imageURL = $imageKit->url(array(
2
'path' => '/default-image.jpg',
3
'transformation' => array(
4
array(
5
'height' => '300',
6
'width' => '400',
7
),
8
),
9
));
10
​
11
echo('Url : ' . $imageURL);
12
// https://ik.imagekit.io/demo/tr:w-400,h-300/default-image.jpg
13
​
Copied!
400x300 image

Quality manipulation

You can use the quality parameter to change quality like this.
1
$imageURL = $imageKit->url(array(
2
'path' => '/default-image.jpg',
3
'transformation' => array(
4
array(
5
'quality' => '40',
6
),
7
),
8
));
9
​
10
echo('Url : ' . $imageURL);
11
// https://ik.imagekit.io/demo/tr:q-40/default-image.jpg
Copied!

Chained transformation

You can pass more than one object in transformation parameter to chain these transformations sequentially.
For example, the following values will first resize the image to width 400, height 300, and then rotate to 90 degrees.
1
$imageURL = $imageKit->url(array(
2
'path' => '/default-image.jpg',
3
4
// It means first resize the image to 400x300 and then rotate 90 degree
5
'transformation' => array(
6
array(
7
'height' => '300',
8
'width' => '400',
9
),
10
array(
11
'rotation' => '90'
12
)
13
),
14
));
15
​
16
echo('Url : ' . $imageURL);
17
// https://ik.imagekit.io/demo/tr:w-400,h-300:rt-90/default-image.jpg
Copied!

Sharpening and contrast transformation

You can enhance images and manipulate colors like this.
1
$imageURL = $imageKit->url(array(
2
'path' => '/sample_image.jpg',
3
4
// It means first resize the image to 400x300 and then rotate 90 degree
5
'transformation' => array(
6
[
7
'format' => 'jpg',
8
'progressive' => true,
9
'effectSharpen' => '-',
10
'effectContrast' => '1',
11
],
12
),
13
));
14
​
15
echo('Url : ' . $imageURL);
16
// https://ik.imagekit.io/demo/tr:f-jpg,pr-true,e-sharpen,e-contrast-1/sample_image.jpg
Copied!

Adding overlays to images in PHP

ImageKit.io allows you to can add text and image overlay dynamically.
For example:
1
$imageURL = $imageKit->url(array(
2
'path' => '/default-image.jpg',
3
'urlEndpoint' => 'https://ik.imagekit.io/pshbwfiho'
4
5
// It means first resize the image to 400x300 and then rotate 90 degree
6
'transformation' => array(
7
array(
8
'height' => '300',
9
'width' => '300',
10
'overlayImage' => 'default-image.jpg',
11
'overlaywidth' => '100',
12
'overlayX' => '0',
13
'overlayImageBorder' => '10_CDDC39' // 10px border of color CDDC39
14
)
15
),
16
));
17
​
18
echo('Url : ' . $imageURL);
19
// https://ik.imagekit.io/pshbwfiho/tr:w-300,h-300,oi-default-image.jpg,ow-100,ox-0,oib-10_CDDC39/default-image.jpg
Copied!

Generating Signed URL for images in PHP

ImageKit.io PHP SDK can generate a secure signed url that allows you to protect your media assets.
For example:
1
$imageURL = $imageKit->url([
2
'path' => '/default-image.jpg',
3
'transformation' => [
4
[
5
'height' => '300',
6
'width' => '400',
7
],
8
],
9
'signed' => true,
10
'expireSeconds' => 300,
11
]);
12
​
13
echo('Signed url : ' . $imageURL);
14
// https://ik.imagekit.io/demo/tr:h-300,w-400/default-image.jpg?ik-t=1632816299&ik-s=ffe7bc9445f95b4e33b4fb25ac504557a4ae03fc
Copied!
You can manage security settings from the dashboard to prevent unsigned URLs usage. In that case, if the URL doesn't have signature ik-s parameter or the signature is invalid, ImageKit will return a forbidden error instead of an actual image.

Server-side file uploading

The SDK provides a simple interface using the $imageKit->upload() method to upload files to the ImageKit Media Library. It accepts all the parameters supported by the ImageKit Upload API.
The uploadFiles() method requires at least the file and the fileName parameter to upload a file and returns a JSON response. You can pass other parameters supported by the ImageKit upload API using the same parameter name as specified in the upload API documentation. For example, to specify tags for a file at the time of upload use the tags parameter as specified in the documentation here.
1
$imageKit->upload(array(
2
"file" => "your_file", // required, can be base64 or binary or a remote url
3
"fileName" => "your_file_name.jpg", // required
4
... // Additional Parameters can be refered to Server Side file Upload Documentation, https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload
5
));
Copied!
If the upload succeeds, error will be null and the result will be the same as what is received from ImageKit's servers. If the upload fails, error will be the same as what is received from ImageKit's servers and the result will be null.

ImageKit Media API

The SDK provides a simple interface for all the media APIs mentioned here to manage your files.

List and search files

Accepts an object specifying the parameters to be used to list and search files. All parameters specified in the documentation here can be passed as is with the correct values to get the results.
1
$listFiles = $imageKit->listFiles(array(
2
'skip' => 0,
3
'limit' => 1,
4
));
Copied!

Get file details

Accepts the file ID and fetches the details as per the API documentation here.
1
$getFileDetails = $imageKit->getFileDetails('file_id');
Copied!

Update file details

Accepts the file ID and fetches the metadata as per the API documentation here.
1
$updateFileDetails = $imageKit->updateFileDetails('file_id',
2
array(
3
'tags' => ['image_tag'],
4
'customCoordinates' => '100,100,100,100'
5
)
6
);
Copied!

Add bulk tags

Add tags to multiple files in a single request as per API documentation here. The method accepts an array of fileIds of the files and an array of tags that have to be added to those files.
1
$fileIds = [ 'file_id_1', 'file_id_2' ];
2
$tags = ['image_tag_1', 'image_tag_2'];
3
​
4
$bulkAddTags = $imageKit->bulkAddTags($fileIds, $tags);
Copied!

Bulk remove tags

Remove tags from multiple files in a single request as per API documentation here. The method accepts an array of fileIds of the files and an array of tags that have to be removed from those files.
1
$fileIds = [ 'file_id_1', 'file_id_2' ];
2
$tags = ['image_tag_1'];
3
​
4
$bulkAddTags = $imageKit->bulkRemoveTags($fileIds, $tags);
Copied!

Delete file

Delete a file as per the API documentation here. The method accepts the file ID of the file that has to be deleted.
1
$imageKit->deleteFile($fileId);
Copied!

Delete files bulk

Deletes multiple files and all their transformations as per the API documentation here. The method accepts the array of file IDs that have to be deleted.
1
$imageKit->bulkFileDeleteByIds(array(
2
"fileIds" => array("file_id_1", "file_id_2", ...)
3
));
Copied!

Copy file

This will copy a file from one location to another as per API documentation here. This method accepts the source file's path and destination folder path.
1
$imagekit->copyFile('/source/path', '/destination/path');
Copied!

Move file

This will move a file from one location to another as per API documentation here. This method accepts the source file's path and destination folder path.
1
$imagekit->moveFile('/source/path', '/destination/path');
Copied!

Rename file

This will rename an already existing file in the media library as per API Documentation here. This method accepts the source file's path, the new name of the file, and an optional boolean parameter to purge the CDN cache after renaming.
Limits on purge Purging has account-level limits. Please refer to purging limits before using this parameter.
1
// Purge Cache would default to false
2
$imagekit->renameFile('/filePath', 'newFileName');
3
​
4
// Purge Cache explicitly set to false
5
$imagekit->renameFile('/filePath', 'newFileName', false);
6
​
7
// Purge Cache explicitly set to true
8
$imagekit->renameFile('/filePath', 'newFileName', true);
Copied!

Create folder

This will create a new folder as per API documentation here. This method accepts the folder name and parent folder path.
1
$imagekit->createFolder('folderName', '/parentFolderPath');
Copied!

Delete folder

This will delete the specified folder and all nested files & folders as per API documentation here. This method accepts the full path of the folder that is to be deleted.
1
$imagekit->deleteFolder('/folderPath');
Copied!

Copy folder

This will copy one folder into another as per API documentation here. This method accepts the source folder's path and destination folder path.
1
$imagekit->copyFolder('/source/path', '/destination/path');
Copied!

Move folder

This will move one folder into another as per API documentation here. This method accepts the source folder's path and destination folder path.
1
$imagekit->moveFolder('/source/path', '/destination/path');
Copied!

Get bulk job status

This allows us to get a bulk operation status e.g. copy or move folder as per API documentation here. This method accepts jobId that is returned by copy and move folder operations.
1
$imagekit->getBulkJobStatus('jobId');
Copied!

Purge cache

Programmatically issue a cache clear request as per the API documentation here. Accepts the full URL of the file for which the cache has to be cleared.
1
$imagekit->purgeCache('image_url');
Copied!

Purge cache status

Get the purge cache request status using the request ID returned when a purge cache request gets submitted as per the API documentation here​
1
$imagekit->getPurgeCacheStatus('request_id');
Copied!

Get file metadata

Accepts the file ID and fetches the metadata as per the API documentation here.
1
$imageKit->getFileMetaData("file_id");
Copied!
You can also get metadata of the image using the absolute image URL. The image URL should be powered by ImageKit and accessible via your account.
1
$imageKit->getFileMetadataFromRemoteURL("imagekit_remote_url");
Copied!

Utility Functions

We have included the following commonly used utility functions in this SDK.

Authentication parameter generation

In case you are looking to implement client-side file upload, you are going to need a token, expiry timestamp and a valid signature for that upload. The SDK provides a simple method that you can use in your code to generate these authentication parameters for you.
The Private API Key should never be exposed in any client-side code. You must always generate these authentication parameters on the server-side.
1
$imageKit->getAuthenticationParameters($token = "", $expire = 0);
Copied!
It will return
1
stdClass Object
2
(
3
[token] => unique_token,
4
[expire] => valid_expiry_timestamp,
5
[signature] => generated_signature
6
)
Copied!
Both the token and expire parameters are optional. If not specified, the SDK generates a random token and also generates a valid expiry timestamp internally. The value of the token and expire used to generate the signature are always returned in the response, no matter if they are provided as an input to this method or not.

Distance calculation between two pHash values

Perceptual hashing allows you to construct a hash value that uniquely identifies an input image based on the contents of an image. ImageKit.io metadata API returns the pHash value of an image in the response. You can use this value to find a duplicate (or similar) image by calculating the distance between the pHash value of the two images.
This SDK exposes pHashDistance function to calculate the distance between two pHash values. It accepts two pHash hexadecimal strings and returns a numeric value indicative of the level of difference between the two images.
1
$imageKit->pHashDistance($firstHash ,$secondHash);
Copied!

Distance calculation examples

1
$imageKit->pHashDistance('f06830ca9f1e3e90', 'f06830ca9f1e3e90');
2
// output: 0 (same image)
3
​
4
$imageKit->pHashDistance('2d5ad3936d2e015b', '2d6ed293db36a4fb');
5
// output: 17 (similar images)
6
​
7
$imageKit->pHashDistance('a4a65595ac94518b', '7838873e791f8400');
8
// output: 37 (dissimilar images)
Copied!
Last modified 24d ago