Hey there, fellow developer! Ready to supercharge your PHP application with Cloudflare's powerful API? Let's dive in and build something awesome together using the cloudflare/sdk package. This guide assumes you're already familiar with PHP and Composer, so we'll keep things snappy and focus on the good stuff.
Before we start, make sure you've got:
First things first, let's get that cloudflare/sdk package installed:
composer require cloudflare/sdk
Easy peasy, right? Now we're cooking with gas!
Time to authenticate with Cloudflare. Grab your API key and email, and let's create a client instance:
use Cloudflare\API\Auth\APIKey; use Cloudflare\API\Adapter\Guzzle; $key = new APIKey('[email protected]', 'your-api-key'); $adapter = new Guzzle($key);
Boom! You're now ready to make some API calls.
Let's start with something simple – listing your zones:
use Cloudflare\API\Endpoints\Zones; $zones = new Zones($adapter); $zoneList = $zones->listZones(); foreach ($zoneList->result as $zone) { echo $zone->name . "\n"; }
Want more details about a specific zone? No problem:
$zoneDetails = $zones->getZoneDetails('zone-id');
Now, let's play with some DNS records:
use Cloudflare\API\Endpoints\DNS; $dns = new DNS($adapter); // Add a record $dns->addRecord('zone-id', 'A', 'example.com', '192.0.2.1'); // Update a record $dns->updateRecordDetails('zone-id', 'record-id', [ 'type' => 'A', 'name' => 'example.com', 'content' => '192.0.2.2' ]); // Delete a record $dns->deleteRecord('zone-id', 'record-id');
Need to clear that cache? We've got you covered:
use Cloudflare\API\Endpoints\Zones; $zones = new Zones($adapter); // Purge everything $zones->purgeAll('zone-id'); // Purge specific URLs $zones->purgeFiles('zone-id', ['https://example.com/style.css']);
Let's beef up security with some firewall rules:
use Cloudflare\API\Endpoints\FirewallRules; $firewallRules = new FirewallRules($adapter); // Create a rule $firewallRules->createRule('zone-id', [ 'filter' => [ 'expression' => 'ip.src eq 192.0.2.1' ], 'action' => 'block' ]); // Update a rule $firewallRules->updateRule('zone-id', 'rule-id', [ 'action' => 'challenge' ]); // Delete a rule $firewallRules->deleteRule('zone-id', 'rule-id');
Don't forget to catch those pesky exceptions:
try { // Your API calls here } catch (\Cloudflare\API\Endpoints\EndpointException $e) { echo "Oops! " . $e->getMessage(); }
Remember, with great power comes great responsibility:
And there you have it! You're now equipped to harness the power of Cloudflare's API in your PHP applications. We've only scratched the surface here, so don't be afraid to dive deeper into the cloudflare/sdk documentation for more advanced features.
Now go forth and build something amazing! And remember, the cloud's the limit when you're working with Cloudflare. Happy coding!