Cloudinary PHP SDK

repository·master·Indexed 19 days ago

https://github.com/cloudinary/cloudinary_php

A library for integrating Cloudinary's media management services into PHP applications. It provides programmatic tools to upload, transform, optimize, and manage images and videos. Key features include the SearchApi for Lucene-like asset queries, AssetDescriptor for metadata management, and AssetTransformation for defining transformation chains. Version 3.x supports PHP 8.0 through 8.4.

Tokens
7.9K
Snippets
27
Records
33
Agent score
64%

What's inside cloudinary_php

  1. Configuration structure and sections

    master

    The Configuration object is composed of several specialized sub-configuration objects. You can access these properties directly to manage specific parts of the SDK setup:

    • $cloud: Cloud-level settings (e.g., cloudName).
    • $api: API credentials (e.g., apiKey, apiSecret).
    • $url: URL-related settings.
    • $tag: Tagging configurations.
    • $responsiveBreakpoints: Cache settings for responsive breakpoints.
    • $authToken: Authentication token settings.
    • $logging: Logging and debug settings.
  2. Configure auto-optimal breakpoints for SrcSet

    master

    When using auto-optimal breakpoint calculation, the SrcSet class relies on the ResponsiveBreakpointsConfig (provided via the main Configuration object) to determine the range and density of images.

    Key parameters used in the calculation:

    • minWidth: The minimum width needed for the image.
    • maxWidth: The maximum width needed for the image.
    • maxImages: The maximum number of breakpoint entries to include in the srcset.
    • autoOptimalBreakpoints: A boolean flag to enable/disable this mode.

    The calculation logic uses a standard RES_DISTRIBUTION (including widths like 750, 828, 1280, 1600, 1920, etc.) and applies a DEFAULT_DPR of 2.0 for widths below the DEFAULT_DPR_THRESHOLD (768px) to ensure high-density displays are supported.

  3. Initialize the Cloudinary SDK

    master

    The Cloudinary class is the main entry point for the SDK. You can initialize it by passing a configuration source to the constructor. Supported configuration sources include an array, a string (typically a path to a configuration file), a Cloudinary\Configuration\Configuration instance, or null to use default settings.

    Upon instantiation, the SDK automatically validates the configuration and prepares internal builders for tags and API access.

    use Cloudinary\Cloudinary;
    use Cloudinary\Configuration\Configuration;
    
    // Option 1: Using an array
    $cloudinary = new Cloudinary([
        'cloud' => [
            'cloud_name' => 'your_cloud_name',
            'api_key'    => 'your_api_key',
            'api_secret' => 'your_api_secret',
        ]
    ]);
    
    // Option 2: Using a Configuration object
    $config = new Configuration(['cloud' => ['cloud_name' => 'your_cloud_name', ...]]);
    $cloudinary = new Cloudinary($config);
  4. Initialize the Cloudinary Configuration

    master

    The Configuration class is the central object for managing SDK settings. You can initialize it using several methods depending on your source of configuration:

    1. Singleton Pattern: Use Configuration::instance() to access a global singleton. This is useful for ensuring consistent configuration across your application. If called for the first time, you can pass a configuration source.
    2. Cloudinary URL: Use Configuration::fromCloudinaryUrl($url) to create a configuration from a cloudinary:// string.
    3. JSON/Array: Use Configuration::fromJson($json) or Configuration::fromParams($params) to initialize from a JSON string or an associative array.
    4. Environment Variable: If no configuration is provided to import() or instance(), the SDK automatically attempts to fall back to the CLOUDINARY_URL environment variable.

    Note on Sensitive Data: When initializing or serializing, you can control whether sensitive keys (like API secrets) are included by setting the $includeSensitive parameter to false.

    use Cloudinary//Configuration;
    
    // Option 1: Using the Singleton with a Cloudinary URL
    $config = Configuration::instance('cloudinary://my_cloud_name:my_api_key:my_api_secret@my_cloud_name');
    
    // Option 2: Using an associative array
    $config = Configuration::fromParams([
        'cloud' => ['cloud_name' => 'my_cloud_name'],
        'api' => ['api_key' => 'my_api_key', 'api_secret' => 'my_api_secret'],
    ]);
    
    // Option 3: Accessing the global singleton later in your code
    $config = Configuration::instance();
  5. Transform and optimize assets

    master

    You can use the SDK to perform transformations like resizing and format optimization on your images and videos. The fluent interface allows you to chain transformation methods.

    $cloudinary->image('sample.jpg')->resize(Resize::fill()->width(100)->height(150))->format(Format::auto());
  6. Configure global URL generation settings

    master

    The UrlConfig class defines the global settings applied when the SDK generates Cloudinary URLs. You can use these settings to control security (HTTPS), CDN usage, URL signing, and asset delivery formats.

    Key configuration areas include:

    Security and HTTPS

    • secure: Force HTTPS URLs even if the page is non-secure. (Default: true)
    • signUrl: Create a URL signed with the first 8 characters of a SHA-1 hash.
    • longUrlSignature: When both longUrlSignature and signUrl are true, the URL is signed using the first 32 characters of a SHA-256 hash.

    CDN and Custom Domains

    • privateCdn: Set to true if you are an Advanced plan user with a private CDN distribution.
    • cname: The custom domain name for building HTTP URLs (relevant for private CDNs).
    • secureCname: The domain name of the CDN distribution for building HTTPS URLs.
    • cdnSubdomain: Automatically build URLs with multiple CDN sub-domains.
    • secureCdnSubdomain: Configuration for secure CDN sub-domains.

    URL Structure and Optimization

    • useRootPath: Omit type and resource_type from the URL.
    • shorten: Use the shorten asset type.
    • forceVersion: Omit the default version string for assets in folders. (Default: true)
    • analytics: Omit analytics data from the URL. (Default: true)
    • responsiveWidth: Enable responsive width.
    • responsiveWidthTransformation: The transformation to use with responsive width. (Default: 'c_limit,w_auto')

    Note: Many of these settings are applied globally to the Cloudinary configuration.

  7. Configure global HTML tag settings via TagConfig

    master

    The TagConfig class defines the global configuration for HTML tags generated by the Cloudinary PHP SDK. You can use these settings to control how responsive images are rendered, how quotes are handled in attributes, and how video posters are formatted.

    Key configuration areas include:

    • Responsive Images: Control whether to generate responsive tags using responsive, responsive_class, responsive_placeholder, and sizes.
    • Attribute Formatting: Control quote types (quotes_type), whether to use a void closing slash (void_closing_slash), and attribute sorting (sort_attributes).
    • Optimization: Enable HiDPI (hidpi), Client Hints (client_hints), or use fetch format transformations (use_fetch_format).
    • Video/Content: Set the video poster image format (video_poster_format) and the delimiter for content items (content_delimiter).
  8. Configure Cloudinary connection settings

    master

    The CloudConfig class defines the mandatory and optional parameters required to connect your application to Cloudinary. These settings are used to authenticate server-side operations and build public URLs for media assets.

    Mandatory Parameters

    • cloudName: The name of your Cloudinary cloud. Required for building public URLs.
    • apiKey: Required for server-side operations to communicate with the Cloudinary API.
    • apiSecret: Required for server-side operations to sign requests.

    Optional Parameters

    • oauthToken: Can be used instead of providing both apiKey and apiSecret.
    • signatureAlgorithm: Sets the signature algorithm (defaults to Utils::ALGO_SHA1).
    • signatureVersion: Sets the signature version (defaults to 2).
    use Cloudinary\Configuration\CloudConfig;
    
    $config = new CloudConfig();
    $config->cloudName = 'your_cloud_name';
    $config->apiKey = 'your_api_key';
    $config->apiSecret = 'your_api_secret';
  9. SDK Version Support and Compatibility

    master

    The current 3.x version of the SDK supports PHP 8.0 through 8.4.

    SDK VersionPHP 5.4PHP 5.5PHP 5.6PHP 7.xPHP 8.0 - 8.3PHP 8.4
    3.x
    2.x✘ *
    1.x
    • Note: 2.x may trigger deprecation warnings on PHP 8.4.