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 quick start guide shows you how to integrate ImageKit into 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:
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.
Let's create a dummy project called sample using composer in a folder.
composer init --name imagekit/sample --type project
It will prompt a few options. Select defaults by pressing enter.
composer require imagekit/imagekit
// Import autoloader from vendor
// If not using PSR-4 is not configured in composer.json file for your project
require_once __DIR__ . '/vendor/autoload.php';
use ImageKit\ImageKit;
// For demonstration purposes, the documentation would use https://ik.imagekit.io/demo as urlEndpoint
$imageKit = new ImageKit(
"publicKey",
"privateKey",
"urlEndpoint"
);
publicKey
andprivateKey
parameters are 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/developer/api-keys.urlEndpoint
is also a required parameter. You can get the value of URL-endpoint from your ImageKit dashboard - https://imagekit.io/dashboard/url-endpoints.
// For URL Generation
$imageURL = $imageKit->url(
[
'path' => '/default-image.jpg',
]
);
echo $imageURL;
// https://ik.imagekit.io/demo/default-image.jpg
// For File Upload
$uploadFile = $imageKit->uploadFile([
'file' => 'file-url',
'fileName' => 'new-file'
]);
{
"error": null,
"result": {
"fileId": "6286329dfef1b033aee60211",
"name": "your_file_name_S-PgGysnR.jpg",
"size": 94466,
"versionInfo": {
"id": "6286329dfef1b033aee60211",
"name": "Version 1"
},
"filePath": "/your_file_name_S-PgGysnR.jpg",
"url": "https://ik.imagekit.io/demo/your_file_name_S-PgGysnR.jpg",
"fileType": "image",
"height": 640,
"width": 960,
"thumbnailUrl": "https://ik.imagekit.io/demo/tr:n-ik_ml_thumbnail/your_file_name_S-PgGysnR.jpg",
"tags": [],
"AITags": null,
"customMetadata": { },
"extensionStatus": {}
},
"responseMetadata":{
"headers":{
"access-control-allow-origin": "*",
"x-ik-requestid": "e98f2464-2a86-4934-a5ab-9a226df012c9",
"content-type": "application/json; charset=utf-8",
"content-length": "434",
"etag": "W/"1b2-reNzjRCFNt45rEyD7yFY/dk+Ghg"",
"date": "Thu, 16 Jun 2022 14:22:01 GMT",
"x-request-id": "e98f2464-2a86-4934-a5ab-9a226df012c9"
},
"raw":{
"fileId": "6286329dfef1b033aee60211",
"name": "your_file_name_S-PgGysnR.jpg",
"size": 94466,
"versionInfo": {
"id": "6286329dfef1b033aee60211",
"name": "Version 1"
},
"filePath": "/your_file_name_S-PgGysnR.jpg",
"url": "https://ik.imagekit.io/demo/your_file_name_S-PgGysnR.jpg",
"fileType": "image",
"height": 640,
"width": 960,
"thumbnailUrl": "https://ik.imagekit.io/demo/tr:n-ik_ml_thumbnail/your_file_name_S-PgGysnR.jpg",
"tags": [],
"AITags": null,
"customMetadata": { },
"extensionStatus": {}
},
"statusCode":200
}
}
ImageKit provides inbuilt media storage and integration with external origins. Refer to the documentation to learn more about URL endpoints and external Image origins supported by ImageKit.
This method allows you to create a URL using the image's path and the ImageKit URL endpoint (urlEndpoint) you want to use to access the image.
$imageURL = $imageKit->url(
[
'path' => '/default-image.jpg',
'transformation' => [
[
'height' => '300',
'width' => '400'
]
]
]
);
https://ik.imagekit.io/demo/tr:h-300,w-400/default-image.jpg
This method allows you to add transformation parameters to an absolute ImageKit-powered URL. This method should be used if you have the absolute URL stored in your database.
$imageURL = $imageKit->url([
'src' => 'https://example.com/default-image.jpg',
'transformation' => [
[
'height' => '300',
'width' => '400'
]
]
]);
https://example.com/tr:h-300,w-400/default-image.jpg
The
$imageKit->url()
method accepts the following parameters.Option | Description |
---|---|
urlEndpoint | Optional. The base URL is to be appended before the path of the image. If not specified, the URL Endpoint specified at the time of SDK initialization is used. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/ |
path | Conditional. This is the path on which the image exists. For example, /path/to/image.jpg . Either the path or src parameter needs to be specified for URL generation. |
src | Conditional. This is the complete URL of an image already mapped to ImageKit. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg . Either the path or src parameter needs to be specified for URL generation. |
transformation | Optional. An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a chained transformation can be specified as different objects of the array. The complete List of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL. |
transformationPosition | Optional. The default value is path which places the transformation string as a path parameter in the URL. It can also be specified as query , which adds the transformation string as the query parameter tr in the URL. If you use the src parameter to create the URL, the transformation string is always added as a query parameter. |
queryParameters | Optional. These are the other query parameters that you want to add to the final URL. These can be any query parameters and are not necessarily related to ImageKit. Especially useful if you want to add some versioning parameters to your URLs. |
signed | Optional. Boolean. The default value is false . If set to true , the SDK generates a signed image URL adding the image signature to the image URL. |
expireSeconds | Optional. Integer. It is used along with the signed parameter. It specifies the time in seconds from now when the signed URL will expire. If specified, the URL contains the expiry timestamp in the URL, and the image signature is modified accordingly. |
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.👉 If the property does not match any of the available options, it is added as it is.\ e.g
[
'effectGray' => 'e-grayscale'
]
// and
[
'e-grayscale' => ''
]
// works the same
👉 Note that you can also use the
h
and w
parameters instead of height
and width
.$imageURL = $imageKit->url([
'path' => '/default-image.jpg',
'urlEndpoint' => 'https://ik.imagekit.io/demo/',
'transformation' => [
[
'height' => '300',
'width' => '400'
],
[
'rotation' => 90
],
],
'transformationPosition' => 'query'
]);
https://ik.imagekit.io/demo/default-image.jpg?tr=h-300,w-400:rt-90
.png?alt=media)
Some transformations like Contrast stretch , Sharpen and Unsharp mask can be added to the URL with or without any other value. To use such transforms without specifying a value, specify the value as "-" in the transformation object. Otherwise, specify the value that you want to be added to this transformation.
$imageURL = $imageKit->url([
'src' => 'https://ik.imagekit.io/demo/default-image.jpg',
'transformation' =>
[
[
'format' => 'jpg',
'progressive' => true,
'effectSharpen' => '-',
'effectContrast' => '1'
]
]
]);
https://ik.imagekit.io/demo/tr:f-jpg,pr-true,e-sharpen,e-contrast-1/default-image.jpg
.png?alt=media)
Let's resize the image to a width of 400 and a height of 300. Check detailed instructions on Resize, Crop, and Other Common Transformations
$imageURL = $imageKit->url(array(
'path' => '/default-image.jpg',
'transformation' => [
[
'height' => '300',
'width' => '400',
]
]
));
https://ik.imagekit.io/demo/tr:w-400,h-300/default-image.jpg
.png?alt=media)
400x300 image
$imageURL = $imageKit->url(array(
'path' => '/default-image.jpg',
'transformation' => [
[
'quality' => '40',
]
]
));
https://ik.imagekit.io/demo/tr:q-40/default-image.jpg
.png?alt=media)
$imageURL = $imageKit->url(array(
'path' => '/default-image.jpg',
'urlEndpoint' => 'https://ik.imagekit.io/pshbwfiho'
// It means first resize the image to 400x300 and then rotate 90 degree
'transformation' => [
[
'height' => '300',
'width' => '300',
'overlayImage' => 'default-image.jpg',
'overlaywidth' => '100',
'overlayX' => '0',
'overlayImageBorder' => '10_CDDC39' // 10px border of color CDDC39
]
]
));
https://ik.imagekit.io/demo/tr:w-300,h-300,oi-default-image.jpg,ow-100,ox-0,oib-10_CDDC39/default-image.jpg
.png?alt=media)
Signed URL that expires in 300 seconds with the default URL endpoint and other query parameters. For a detailed explanation of the Signed URL refer to this Official Doc.
$imageURL = $imageKit->url([
"path" => "/default-image.jpg",
"queryParameters" =>
[
"v" => "123"
],
"transformation" => [
[
"height" => "300",
"width" => "400"
]
],
"signed" => true,
"expireSeconds" => 300,
]);
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400/default-image.jpg?v=123&ik-t=1654183277&ik-s=f98618f264a9ccb3c017e7b7441e86d1bc9a7ebb
You can manage Security Settings from the dashboard to prevent unsigned URLs usage. In that case, if the URL doesn't have a signature
ik-s
parameter or the signature is invalid, ImageKit will return a forbidden error instead of an actual image.The complete list of transformations supported and their usage in ImageKit can be found here. The SDK gives a name to each transformation parameter, making the code simpler and readable. If a transformation is supported in ImageKit, but a name for it cannot be found in the table below, use the transformation code from ImageKit docs as the name when using it in the
url
function.Supported Transformation Name | Translates to parameter |
---|---|
height | h |
width | w |
aspectRatio | ar |
quality | q |
crop | c |
cropMode | cm |
x | x |
y | y |
focus | fo |
format | f |
radius | r |
background | bg |
border | b |
rotation | rt |
blur | bl |
named | n |
overlayX | ox |
overlayY | oy |
overlayFocus | ofo |
overlayHeight | oh |
overlayWidth | ow |
overlayImage | oi |
overlayImageTrim | oit |
overlayImageAspectRatio | oiar |
overlayImageBackground | oibg |
overlayImageBorder | oib |
overlayImageDPR | oidpr |
overlayImageQuality | oiq |
overlayImageCropping | oic |
overlayImageFocus | oifo |
overlayImageTrim | oit |
overlayText | ot |
overlayTextFontSize | ots |
overlayTextFontFamily | otf |
overlayTextColor | otc |
overlayTextTransparency | oa |
overlayAlpha | oa |
overlayTextTypography | ott |
overlayBackground | obg |
overlayTextEncoded | ote |
overlayTextWidth | otw |
overlayTextBackground | otbg |
overlayTextPadding | otp |
overlayTextInnerAlignment | otia |
overlayRadius | or |
progressive | pr |
lossless | lo |
trim | t |
metadata | md |
colorProfile | cp |
defaultImage | di |
dpr | dpr |
effectSharpen | e-sharpen |
effectUSM | e-usm |
effectContrast | e-contrast |
effectGray | e-grayscale |
original | orig |
raw | replaced by the parameter value |
The SDK provides a simple interface using the
$imageKit->uploadFile()
or $imageKit->uploadFile()
method to upload files to the ImageKit Media Library.$uploadFile = $imageKit->uploadFile([
'file' => 'your_file', // required, "binary","base64" or "file url"
'fileName' => 'your_file_name.jpg', // required
]);
{
"error": null,
"result": {
"fileId": "6286329dfef1b033aee60211",
"name": "your_file_name_S-PgGysnR.jpg",
"size": 94466,
"versionInfo": {
"id": "6286329dfef1b033aee60211",
"name": "Version 1"
},
"filePath": "/your_file_name_S-PgGysnR.jpg",
"url": "https://ik.imagekit.io/demo/your_file_name_S-PgGysnR.jpg",
"fileType": "image",
"height": 640,
"width": 960,
"thumbnailUrl": "https://ik.imagekit.io/demo/tr:n-ik_ml_thumbnail/your_file_name_S-PgGysnR.jpg",
"tags": [],
"AITags": null,
"customMetadata": { },
"extensionStatus": {}
},
"responseMetadata":{
"headers":{
"access-control-allow-origin": "*",
"x-ik-requestid": "e98f2464-2a86-4934-a5ab-9a226df012c9",
"content-type": "application/json; charset=utf-8",
"content-length": "434",
"etag": "W/"1b2-reNzjRCFNt45rEyD7yFY/dk+Ghg"",
"date": "Thu, 16 Jun 2022 14:22:01 GMT",
"x-request-id": "e98f2464-2a86-4934-a5ab-9a226df012c9"
},
"raw":{
"fileId": "6286329dfef1b033aee60211",
"name": "your_file_name_S-PgGysnR.jpg",
"size": 94466,
"versionInfo": {
"id": "6286329dfef1b033aee60211",
"name": "Version 1"
},
"filePath": "/your_file_name_S-PgGysnR.jpg",
"url": "https://ik.imagekit.io/demo/your_file_name_S-PgGysnR.jpg",
"fileType": "image",
"height": 640,
"width": 960,
"thumbnailUrl": "https://ik.imagekit.io/demo/tr:n-ik_ml_thumbnail/your_file_name_S-PgGysnR.jpg",
"tags": [],
"AITags": null,
"customMetadata": { },
"extensionStatus": {}
},
"statusCode":200
}
}
Please refer to Server Side File Upload - Request Structure for detailed explanation about mandatory and optional parameters.
// Attempt File Uplaod
$uploadFile = $imageKit->uploadFile([
'file' => 'your_file', // required, "binary","base64" or "file url"
'fileName' => 'your_file_name.jpg', // required
// Optional Parameters
"useUniqueFileName" => true, // true|false
"tags" => implode(",",["abd", "def"]), // max: 500 chars
"folder" => "/sample-folder",
"isPrivateFile" => false, // true|false
"customCoordinates" => implode(",", ["10", "10", "100", "100"]), // max: 500 chars
"responseFields" => implode(",", ["tags", "customMetadata"]),
"extensions" => [
[
"name" => "remove-bg",
"options" => [ // refer https://docs.imagekit.io/extensions/overview
"add_shadow" => true
]
]
],
"webhookUrl" => "https://example.com/webhook",
"overwriteFile" => true, // in case of false useUniqueFileName should be true
"overwriteAITags" => true, // set to false in order to preserve overwriteAITags
"overwriteTags" => true,
"overwriteCustomMetadata" => true,
// "customMetadata" => [
// "SKU" => "VS882HJ2JD",
// "price" => 599.99,
// ]
]);
Refer to the List and Search File API for a better understanding of the Request & Response Structure.
$listFiles = $imageKit->listFiles();
Filter out the files with an object specifying the parameters.
$listFiles = $imageKit->listFiles([
"type" => "file", // file, file-version or folder
"sort" => "ASC_CREATED",
"path" => "/", // folder path
"fileType" => "all", // all, image, non-image
"limit" => 10, // min:1, max:1000
"skip" => 0, // min:0
"searchQuery" => 'size < "20kb"',
]);
In addition, you can fine-tune your query by specifying various filters by generating a query string in a Lucene-like syntax and providing this generated string as the value of the
searchQuery
.$listFiles = $imageKit->listFiles([
"searchQuery" => '(size < "1mb" AND width > 500) OR (tags IN ["summer-sale","banner"])',
]);
This API can get you all the details and attributes of the current version of the file.
$getFileDetails = $imageKit->getFileDetails('file_id');
This API can get you all the details and attributes for the provided version of the file.
versionID
can be found in the following APIs as id
within the versionInfo
parameter:Refer to the Get File Version Details API for a better understanding of the Request & Response Structure.
$getFileVersionDetails = $imageKit->getFileVersionDetails('file_id','version_id');
This API can get you all the versions of the file.
$getFileVersions = $imageKit->getFileVersions('file_id');
Update file details such as tags, customCoordinates attributes, remove existing AITags, and apply extensions using Update File Details API. This operation can only be performed on the current version of the file.
Refer to the Update File Details API for better understanding about the Request & Response Structure.
// Update parameters
$updateData = [
"removeAITags" => "all", // "all" or ["tag1","tag2"]
"webhookUrl" => "https://example.com/webhook",
"extensions" => [
[
"name" => "remove-bg",
"options" => [ // refer https://docs.imagekit.io/extensions/overview
"add_shadow" => true
]
],
[
"name" => "google-auto-tagging",
]
],
"tags" => ["tag1", "tag2"],
"customCoordinates" => "10,10,100,100",
// "customMetadata" => [
// "SKU" => "VS882HJ2JD",
// "price" => 599.99,
// ]
];
// Attempt Update
$updateFileDetails = $imageKit->updateFileDetails(
'file_id',
$updateData
);
Add tags to multiple files in a single request. The method accepts an array of
fileIds
of the files and an array of tags
that have to be added to those files.$fileIds = ['file_id1','file_id2'];
$tags = ['image_tag_1', 'image_tag_2'];
$bulkAddTags = $imageKit->bulkAddTags($fileIds, $tags);
Remove tags from multiple files in a single request. The method accepts an array of
fileIds
of the files and an array of tags
that have to be removed from those files.$fileIds = ['file_id1','file_id2'];
$tags = ['image_tag_1', 'image_tag_2'];
$bulkRemoveTags = $imageKit->bulkRemoveTags($fileIds, $tags);
Remove AI tags from multiple files in a single request. The method accepts an array of
fileIds
of the files and an array of AITags
that have to be removed from those files.Refer to the Remove AI Tags (Bulk) API for a better understanding of the Request & Response Structure.
$fileIds = ['file_id1','file_id2'];
$AITags = ['image_AITag_1', 'image_AITag_2'];
$bulkRemoveTags = $imageKit->bulkRemoveTags($fileIds, $AITags);