<?php
define('CLOUDFLARE_ACCOUNT_ID', '<place your Cloudflare account ID here>');
define('CLOUDFLARE_API_KEY', '<place your Cloudflare API key here>');
define('CLOUDFLARE_API_URL', 'https://<ACCOUNT_ID>.r2.cloudflarestorage.com');
// Utility function to handle Cloudflare R2 authentication and API requests
function cloudflare_api_request($endpoint, $method = 'GET', $headers = [], $body = null) {
$ch = curl_init();
// Set the URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, CLOUDFLARE_API_URL . $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Include body if it's a POST request
if ($method === 'POST' && $body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
// Execute and close the cURL session
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
// Function to generate a presigned URL for Cloudflare R2 buckets
function cloudflare_generate_presigned_url($resourcePath, $expires, $method = 'GET') {
// Calculate expiry time
$expiresAt = time() + $expires;
// Construct the presigned URL
$presignedUrl = CLOUDFLARE_API_URL . '/' . $resourcePath . '?X-Amz-Date=' . time() . '&X-Amz-Expires=' . $expiresAt;
// Add signature to the URL (this is a placeholder, actual implementation required)
// $signature = generate_signature($resourcePath, $expiresAt); // Implement this function based on Cloudflare's signing algorithm
// $presignedUrl .= '&X-Amz-Signature=' . $signature;
return $presignedUrl;
}
// Example usage of the API request function
$response = cloudflare_api_request('/your-endpoint', 'GET');
// Example usage of the presigned URL function
$presignedUrl = cloudflare_generate_presigned_url('path/to/resource', 3600); // 3600 seconds = 1 hour