Cloudflare PHP SDK

repository·master·Indexed 20 days ago

https://github.com/cloudflare/cloudflare-php

A community-maintained PHP SDK for Cloudflare API v4, allowing developers to programmatically manage resources such as DNS, WAF, Zones, Origin CA certificates, Custom Hostnames, and DNS Analytics. Requires PHP 8.1 or later and is available via Composer as `cloudflare/sdk`.

Tokens
9.4K
Snippets
36
Records
46
Agent score
70%

What's inside cloudflare-php

  1. Understand the Cloudflare API endpoint structure

    master

    The SDK maps Cloudflare API calls to functions within specific classes located in the Cloudflare\API\Endpoints namespace.

    Supported endpoint categories include:

    • DNS Records
    • DNS Analytics
    • Zones
    • User Administration (partial)
    • Cloudflare IPs
    • Page Rules
    • Web Application Firewall (WAF)
    • Custom hostnames
    • Manage TLS settings
    • Zone Lockdown and User-Agent Block rules
    • Railgun administration
    • Origin CA
    • Crypto
    • Load Balancers
    • Firewall Settings

    Note: This is a community-maintained SDK covering a subset of the Cloudflare API. For full API coverage, use the Cloudflare API directly.

  2. Get started with the Cloudflare SDK

    master

    To use the SDK, you must initialize an authentication key, an HTTP adapter (Guzzle is provided), and then instantiate the specific endpoint class you wish to interact with.

    1. Create a Cloudflare\API\Auth\APIKey instance with your email and API key.
    2. Create a Cloudflare\API\Adapter\Guzzle instance passing the authentication key.
    3. Instantiate the desired endpoint class (e.g., Cloudflare\API\Endpoints\User) by passing the adapter to its constructor.
    $key     = new Cloudflare\API\Auth\APIKey('user@example.com', 'apiKey');
    $adapter = new Cloudflare\API\Adapter\Guzzle($key);
    $user    = new Cloudflare\API\Endpoints\User($adapter);
    
    echo $user->getUserID();
  3. Configure Certificate settings

    master

    The Cloudflare\API\Configurations\Certificate class is used to define settings for a certificate request. You can specify the hostnames, validity period, signature type, and the Certificate Signing Request (CSR).

    Configuration Options

    • Hostnames: An array of hostnames or wildcard names (e.g., *.example.com) bound to the certificate. Use setHostnames(array $hostnames).
    • Requested Validity: The number of days for which the certificate should be valid. Use setRequestedValidity(int $validity).
      • Default: 5475
      • Valid values: 7, 30, 90, 365, 730, 1095, 5475
    • Request Type: The signature type desired on the certificate. Use setRequestType(string $type).
      • Valid values: origin-rsa, origin-ecc, keyless-certificate.
      • Constants: Use Certificate::ORIGIN_RSA, Certificate::ORIGIN_ECC, or Certificate::KEYLESS_CERTIFICATE for type safety.
    • CSR: The Certificate Signing Request. Must be newline-encoded. Use setCsr(string $csr).
    use Cloudflare\API\Configurations\Certificate;
    
    $certificate = new Certificate();
    $certificate->setHostnames(['example.com', 'foo.example.com']);
    $certificate->setRequestedValidity(365);
    $certificate->setRequestType(Certificate::ORIGIN_RSA);
    $certificate->setCsr("-----BEGIN CERTIFICATE REQUEST-----\n...\n-----END CERTIFICATE REQUEST-----");
    
    $configArray = $certificate->getArray();
  4. Manage TLS settings for a zone

    master

    The Cloudflare\API\Endpoints\TLS class provides methods to manage TLS-related configurations for a specific Cloudflare zone. You can control TLS 1.3 availability, set the minimum TLS version, and manage TLS Client Authentication settings.

    use Cloudflare\API\Adapter\Adapter;
    use Cloudflare\API\Endpoints\TLS;
    
    // Assuming $adapter is already instantiated with your credentials
    $tls = new TLS($adapter);
    
    // Enable TLS 1.3
    $tls->enableTLS13('your_zone_id');
    
    // Change minimum TLS version
    $tls->changeMinimumTLSVersion('your_zone_id', '1.2');
    
    // Get current TLS Client Auth setting
    $clientAuth = $tls->getTLSClientAuth('your_zone_id');
  5. Manage Origin CA certificates

    master

    The Cloudflare\API\Endpoints\Certificates class provides methods to manage Origin CA certificates within a specific zone. You can list all certificates, retrieve a specific certificate by its ID, revoke a certificate, or create a new one using a CertificateConfig object.

    use Cloudflare\API\Endpoints\Certificates;
    use Cloudflare\API\Configurations\Certificate as CertificateConfig;
    
    // Assuming $adapter is already instantiated
    $certificatesEndpoint = new Certificates($adapter);
    
    // 1. List all certificates for a zone
    $list = $certificatesEndpoint->listCertificates('YOUR_ZONE_ID');
    
    // 2. Get a specific certificate
    $cert = $certificatesEndpoint->getCertificate('CERTIFICATE_ID', 'YOUR_ZONE_ID');
    
    // 3. Create a new certificate
    $config = new CertificateConfig();
    // ... configure $config ...
    $success = $certificatesEndpoint->createCertificate($config);
    
    // 4. Revoke a certificate
    $revoked = $certificatesEndpoint->revokeCertificate('CERTIFICATE_ID', 'YOUR_ZONE_ID');
  6. Update a Custom Hostname

    master

    Use updateHostname to modify the configuration of an existing custom hostname. Only the parameters you provide will be updated.

    Parameters:

    • string $zoneID: The ID of the zone.
    • string $hostnameID: The ID of the hostname to update.
    • string $sslMethod: New SSL method.
    • string $sslType: New SSL type.
    • array $sslSettings: New SSL settings.
    • string $customOriginServer: New custom origin server.
    • bool|null $wildcard: New wildcard status.
    • string $bundleMethod: New SSL bundle method.
    • array $customSsl: New custom SSL credentials ('key' and 'certificate').

    Returns: \stdClass containing the updated result.

    $result = $customHostnames->updateHostname(
        'zone_id_123',
        'hostname_id_456',
        'https',
        'dv',
        [],
        'new-origin.example.com'
    );
  7. List Custom Hostnames

    master

    Use listHostnames to retrieve a list of custom hostnames associated with a zone. The results are paginated.

    Parameters:

    • string $zoneID: The ID of the zone.
    • string $hostname: Filter by hostname.
    • string $hostnameID: Filter by specific hostname ID.
    • int $page: Page number (default: 1).
    • int $perPage: Number of results per page (default: 20).
    • string $order: Sort order.
    • string $direction: Sort direction.
    • int $ssl: SSL filter.

    Returns: An (object) containing result (the list of hostnames) and result_info (pagination metadata).

    $response = $customHostnames->listHostnames(
        'zone_id_123',
        '',
        '',
        1,
        50
    );
    
    $hostnames = $response->result;
    $info = $response->result_info;
  8. Manage SSL and HTTPS settings via the SSL endpoint

    master

    The Cloudflare\API\Endpoints\SSL class provides methods to retrieve and update SSL/TLS and HTTPS settings for a specific zone.

    Available Settings

    • SSL Setting: Controls the SSL mode for the zone.
    • HTTPS Redirect: Controls the always_use_https setting.
    • HTTPS Rewrites: Controls the automatic_https_rewrites setting.

    SSL Verification

    You can check the SSL verification status for a zone. The getSSLVerificationStatus method accepts an optional $retry boolean parameter to immediately trigger a retry of the SSL verification process.

  9. Retrieve DNS Analytics report grouped by time

    master

    Use getReportByTime to retrieve aggregate metrics grouped by a specific time interval. This method utilizes a configuration object internally to manage parameters.

    Required Parameters:

    • zoneID: The ID of the zone to report on.
    • dimensions: An array of dimension names.
    • metrics: An array of metric names.
    • since: Start date and time in ISO8601 format.
    • until: End date and time in ISO8601 format.

    Optional Parameters:

    • sort: An array of dimension names to sort by, prefixed by order: - for descending or + for ascending.
    • filters: A segmentation filter string in 'attribute operator value' format.
    • limit: The maximum number of returned metrics (defaults to 100).
    • timeDelta: The unit of time to group data by.

    Returns a stdClass containing the result field from the API response.

    $dnsAnalytics = new \Cloudflare\API\Endpoints\DNSAnalytics($adapter);
    $report = $dnsAnalytics->getReportByTime(
        'zone_id_here',
        ['dimension_name'],
        ['metric_name'],
        ['+dimension_name'],
        'attribute operator value',
        '2023-01-01T00:00:00Z',
        '2023-01-02T00:00:00Z',
        100,
        '1h'
    );
  10. Purge Cloudflare Cache

    master

    You can clear cached content for a zone using specific purge methods. Both methods support an $includeEnvironments flag to also purge cache across all Cloudflare environments associated with the zone.

    • Purge Everything: cachePurgeEverything(string $zoneID, bool $includeEnvironments = false): bool clears the entire cache for the zone.
    • Targeted Purge: cachePurge(string $zoneID, ?array $files = null, ?array $tags = null, ?array $hosts = null, bool $includeEnvironments = false): bool allows for granular purging.
      • You must provide at least one of $files, $tags, or $hosts.
      • $files: An array of specific file URLs to purge.
      • $tags: An array of Cache-Tags to purge.
      • $hosts: An array of hostnames to purge.
    // Purge specific files
    $zones->cachePurge('zone_id_here', ['https://example.com/style.css', 'https://example.com/script.js']);
    
    // Purge everything including environments
    $zones->cachePurgeEverything('zone_id_here', true);