Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

Integrating Cloudinary to your backend using a PHP Solution

Published on by

Integrating Cloudinary to your backend using a PHP Solution image

TLDR The web is filled with media content, especially images and video. Manipulating these content effectively over different forms of internet connections require some sort of skilled approach. Cloudinary is a cloud-based service that provides an end-to-end image and video management solution including upload, storage, administration, manipulation and delivery. In this post, I’ll show you how to use PHP to upload and manipulate your images and files with Cloudinary.

Cloudinary provides an API for uploading images and any other kind of files to the cloud. These files are safely stored in the cloud with secure backups and revision history.

Cloudinary already takes away the pain of having to write large amounts of code to interact with their API by providing an open source PHP library that ships with simple,easy-to-use helper methods for:

  1. Image uploading
  2. Image administration and sprite generation
  3. Embedding of images
  4. Building URLs for image transformation and manipulation

What are we waiting for? Let’s get started on how to upload images with PHP using Cloudinary!

  1. Sign up for a free Cloudinary Account
![Cloudinary.com](https://i1.wp.com/wp.laravel-news.com/wp-content/uploads/2016/11/image00.png?resize=525%2C384)
Cloudinary.com
![image02](https://i1.wp.com/wp.laravel-news.com/wp-content/uploads/2016/11/image02.png?resize=525%2C384)

Cloudinary Dashboard …Your cloud name, API Key, API Secret are key valuables to interact with Cloudinary functionalities.

  1. Fetch the Cloudinary PHP library

The second step to uploading your images to Cloudinary using PHP is fetching the library. Modern PHP development involves using Composer. If you prefer the old way, navigate here, make sure you copy all those files and paste them in your app, then reference them similarly to the way it is here.

  1. Server side Upload

You can upload images or any file to Cloudinary from your PHP code running on at least a PHP 5.3 Server. First, we have to set up our key valuables using the config method, so that Cloudinary can recognize that it’s a valid account like so:

\Cloudinary::config(array(
"cloud_name" => "my_cloud_name",
"api_key" => "my_api_key",
"api_secret" => "my_api_secret"
));

Note: I’ll advise you load these key valuables from an environment file(.env) to avoid people getting hold of your config details.

You can put this in a file called settings.php and just include it in the script that performs the actual uploading.

Now, you can use the following methods to upload images/files to Cloudinary’s Cloud platform:

Uploading a local file? Here, you go:

\Cloudinary\Uploader::upload("/home/my_image.jpg")

Uploading a file from a remote HTTP(s) url? Here, you go:

\Cloudinary\Uploader::upload("http://www.example.com/image.jpg")

Uploading a file from an S3 bucket? Here, you go:

\Cloudinary\Uploader::upload('s3://my-bucket/my-path/my-file.jpg');

Note: Every file uploaded to Cloudinary is assigned a Public ID, that can later be used for transformation and delivery.

The syntax for uploading your files with PHP to Cloudinary can be found below:

public static function upload($file, $options = array())

Let’s cover a few examples of what can be passed to the $options array argument.

You want to specify a custom Public ID?, Here, you go:

\Cloudinary\Uploader::upload('my_image.jpg', array("public_id" => "manutd_id"));

You want to preserve and use the original name of the uploaded file? Here, you go:

\Cloudinary\Uploader::upload('sample.jpg', array("use_filename" => TRUE));

Not sure whether a user will upload an image or a raw file? Here, you go:

\Cloudinary\Uploader::upload("spreadsheet.xls", array("resource_type" => "auto"));

Note: Check here for several upload options to use!

  1. Transformation and Manipulation

You can manipulate and transform the images that have already been uploaded to Cloudinary. You can also transform your images or files before storing them in Cloudinary by applying incoming transformation as part of the upload request.

  • Limit the dimension of an uploaded image, then add a watermark as an overlay
\Cloudinary\Uploader::upload('/home/my_image.jpg',
[
"transformation" => [
["width" => 1000, "height" => 1000, "crop" => "limit"],
["overlay" => "my_watermark", "flags" => "relative", "width" => 0.5]
]
]
);
  • Force format conversion to PNG. Also perform custom coordinates cropping
\Cloudinary\Uploader::upload('/home/my_image.jpg',[
"width" => 400, "height" => 300,
"x" => 50, "y" => 80,
"crop" => "crop", "format" => "png"
]);
  • Eagerly transform images by specifying the eager upload option.This example generates a 150 x 100 face detection based thumbnail
Cloudinary::Uploader.upload('/home/my_image.jpg', [
'public_id' => 'eagerly_generated_example',
'eager' => [ 'width' => 150, 'height' => 100, 'crop' => 'thumb', 'gravity' => 'face']
]);

Cloudinary’s upload works synchronously. You can tell Cloudinary to generate eager transformations in the background and send you an HTTP notification callback when the transformations are ready.

\Cloudinary\Uploader::upload('/home/my_image.jpg', [
"eager" => ["width" => 150, "height" => 100,
"crop" => "thumb", "gravity" => "face"],
"eager_async" => true,
"eager_notification_url" => "http://mysite/my_notification_endpoint"
]);

Cloudinary can also perform an asynchronous HTTP GET request to your server when the upload is complete by setting a notification_url parameter.

\Cloudinary\Uploader::upload('/home/my_image.jpg', ["notification_url" => "http://mysite/my_notification_endpoint"])

You can learn more about webhooks, background image processing and upload notifications here.

  1. Form Helpers

With PHP, you can just call several methods via the help of Cloudinary library to assist with uploading of images and files.

Embed a file input tag in your HTML pages

<form action="uploaded.php" method="post">
<?php echo cl_image_upload_tag('image_id', array("callback" => $cors_location)); ?>
</form>

Display uploaded image in your page with it’s Public ID

<?php echo cl_image_tag($photo["public_id"],
array("format" => "jpg", "crop" => "fill", "width" => 120, "height" => 80)); ?>

This file contains more helper tags that you can use while trying to upload images to Cloudinary using PHP.

Looking for a more comprehensive documentation? Check here.

A sample project, which involves creating a photo album can be found here. Clone the repo, get up and running within a few seconds!

PHP Frameworks Integration

In the real world, several programmers employ frameworks to do hasten the application development process. There are libraries that have been written to do the heavy lifting for you, so that you can just focus on building the core logic of your application.

Laravelhttps://github.com/jrm2k6/cloudder

CakePHPhttps://github.com/cloudinary/cloudinary_cake_php

Symfonyhttps://github.com/Speicher210/CloudinaryBundle

Lumenhttps://github.com/nordsoftware/lumen-cloudinary

WordPresshttps://github.com/cloudinary/cloudinary_wordpress

Conclusion

The managing and manipulation of images can become really complex during application development. Best practices support offloading image storage, and manipulation to a reliable service. Cloudinary can effortlessly manage your entire web application’s image pipeline, from your small app to a very large high-traffic application.


Many thanks to Cloudinary for sponsoring Laravel News this week.

Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Register now for Sentry Launch Week! image

Register now for Sentry Launch Week!

Read article
Hide and safeguard emails from bots with the Muddle Laravel package image

Hide and safeguard emails from bots with the Muddle Laravel package

Read article
Dynamic Cache, Database, and Mail Builders in Laravel 11.31 image

Dynamic Cache, Database, and Mail Builders in Laravel 11.31

Read article