softare development

How to Integrate Cloudinary with PHP

Cloudinary is a powerful cloud-based media management platform that allows you to upload, store, manage, manipulate, and deliver images and videos for your websites and apps. In this guide, I’ll walk you through the process of integrating Cloudinary with your PHP application.

Prerequisites

  • A Cloudinary account (sign up at cloudinary.com if you don’t have one)
  • PHP 7.0 or higher installed on your server
  • Composer (PHP dependency manager)
  • Basic knowledge of PHP

Step 1: Install the Cloudinary PHP SDK

First, you’ll need to install the official Cloudinary PHP SDK using Composer.

  1. Open your terminal or command prompt.
  2. Navigate to your project directory.
  3. Run the following command:
composer require cloudinary/cloudinary_php

This will install the Cloudinary PHP SDK and all its dependencies in your project’s vendor directory.

Step 2: Set Up Your Cloudinary Configuration

After installing the SDK, you need to configure it with your Cloudinary account credentials.

  1. Log in to your Cloudinary dashboard.
  2. From the dashboard, note down your:
  • Cloud name
  • API Key
  • API Secret

Important: Keep your API secret secure and never expose it in client-side code.

  1. Create a configuration file (e.g., cloudinary_config.php) in your project:
<?php
require 'vendor/autoload.php';

use Cloudinary\Configuration\Configuration;
use Cloudinary\Api\Upload\UploadApi;

// Configure Cloudinary
Configuration::instance([
    'cloud' => [
        'cloud_name' => 'your_cloud_name',
        'api_key' => 'your_api_key',
        'api_secret' => 'your_api_secret'
    ],
    'url' => [
        'secure' => true
    ]
]);

Replace 'your_cloud_name', 'your_api_key', and 'your_api_secret' with your actual Cloudinary credentials.

Step 3: Create a Simple Upload Form

Now, let’s create a simple HTML form to upload images to Cloudinary.

  1. Create a file named upload_form.php:
<!DOCTYPE html>
<html>
<head>
    <title>Cloudinary PHP Upload</title>
</head>
<body>
    <h1>Upload Image to Cloudinary</h1>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="image" accept="image/*" required>
        <button type="submit">Upload</button>
    </form>
</body>
</html>

Step 4: Create the Upload Handler

Next, create the PHP script that will handle the file upload to Cloudinary.

  1. Create a file named upload.php:
<?php
require 'cloudinary_config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
    try {
        // Get the temporary file path
        $filePath = $_FILES['image']['tmp_name'];

        // Upload the image to Cloudinary
        $upload = (new UploadApi())->upload($filePath, [
            'folder' => 'php_uploads/',
            'public_id' => 'img_' . time(),
            'overwrite' => true,
            'resource_type' => 'image'
        ]);

        // Display the uploaded image
        echo "<h1>Upload Successful!</h1>";
        echo "<p>Public ID: " . htmlspecialchars($upload['public_id']) . "</p>";
        echo "<p>Secure URL: " . htmlspecialchars($upload['secure_url']) . "</p>";
        echo "<img src='" . htmlspecialchars($upload['secure_url']) . "' width='500'>";

    } catch (Exception $e) {
        echo "<h1>Upload Failed</h1>";
        echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    }
} else {
    header('Location: upload_form.php');
    exit;
}

Step 5: Test Your Integration

  1. Start your local PHP server (if testing locally):
   php -S localhost:8000
  1. Open your browser and navigate to http://localhost:8000/upload_form.php
  2. Select an image file and click “Upload”
  3. If everything is configured correctly, you should see the uploaded image with its Cloudinary URL

Advanced Features

1. Image Transformations

Cloudinary allows you to apply transformations to your images on the fly. Here’s how to generate a transformed image URL:

$transformedUrl = cloudinary_url($upload['public_id'], [
    'width' => 300,
    'height' => 200,
    'crop' => 'fill',
    'effect' => 'sepia',
    'quality' => 'auto'
]);

echo "<img src='" . htmlspecialchars($transformedUrl) . "'>";

2. Deleting an Image

To delete an uploaded image:

<?php
require 'cloudinary_config.php';

$publicId = 'php_uploads/img_1234567890'; // Replace with your actual public ID

try {
    $result = (new UploadApi())->destroy($publicId);
    echo "Image deleted successfully: " . print_r($result, true);
} catch (Exception $e) {
    echo "Error deleting image: " . $e->getMessage();
}

3. Listing Resources

To list all uploaded images in a specific folder:

<?php
require 'cloudinary_config.php';

try {
    $resources = (new AdminApi())->assets([
        'type' => 'upload',
        'prefix' => 'php_uploads/',
        'max_results' => 10
    ]);

    echo "<h1>Uploaded Images</h1>";
    foreach ($resources['resources'] as $resource) {
        echo "<img src='" . htmlspecialchars($resource['secure_url']) . "' width='200'><br>";
        echo "Public ID: " . htmlspecialchars($resource['public_id']) . "<br><br>";
    }
} catch (Exception $e) {
    echo "Error listing resources: " . $e->getMessage();
}

Security Considerations

  1. Never expose your API secret in client-side code.
  2. For production, consider:
  • Storing credentials in environment variables
  • Implementing server-side validation for uploads
  • Setting upload limits (file size, type, etc.)
  1. Use Cloudinary’s signing mechanism for secure transformations if needed.

Conclusion

You’ve now successfully integrated Cloudinary with your PHP application! This gives you powerful media management capabilities including:

  • Secure cloud storage for your images and videos
  • On-the-fly image transformations
  • Automatic optimization and format conversion
  • CDN delivery for fast loading times

From here, you can explore more advanced features like:

  • Video uploads and transformations
  • Automatic tagging and moderation
  • AI-based image analysis
  • Advanced delivery options

Remember to check the official Cloudinary PHP SDK documentation for more detailed information and advanced usage.

Recent Posts

Event Delegation in JavaScript

Imagine you’re the principal of a large school. Every day, students (like buttons, links, or…

24 hours ago

The DRY Concept (Don’t Repeat Yourself)

You know that thing you do? Where you copy a chunk of code, paste it…

4 days ago

What Truly Makes a Great Software Developer

We've all seen them. The developers who seem to effortlessly untangle complex problems, whose code…

7 days ago

How to Filter Vulgar Words in React Native

If you're building a social, chat, or comment-based mobile app using React Native, protecting your…

2 weeks ago

How to Build Faster Mobile Apps With Native Wind Library

The Cross-Platform ImperativeLet's face it: building separate iOS and Android apps wastes resources. React Native…

2 weeks ago

The Surprisingly Simple Secret to Getting Things Done

We live in an age of infinite distraction and overwhelming ambition. Grand goals shimmer on…

2 weeks ago