Wildcard subdomains on Cloudflare with PHP and API-tokens

I have been using Cloudflare’s excellent DNS-service for managing my domains. Free SSL-certificates and anti-DDoS services are added benefits.

However, proxied wildcard subdomains are not available except on the enterprise plan. If you are reading this blog, you probably cannot afford id :-) But you can still use wildcards in their dns, but you have to manage the SSL-part your self. Laravel Forge has Let’s Encrypt-wildcard has support, but it’s limited to 50 subdomains, where Cloudflare has a limit of 1000 subdomains.

How to solve this? You can use Cloudflare’s API to update the DNS-records by your self (1000 record limit).

Let’s set this up!

PHP

Cloudflare provies a PHP sdk for developers which we can use for the time being.

composer require cloudflare/sdk

But all documentation and examples uses API-Key, which has no granualar permissions. It has full access to your account, which we do not want.

First create a API-token: My Profile > API Tokens > Create token

I am going to settle with Zone.Zone Settings, Zone.Zone, Zone.DNS and set Zone Resource > Include > Specific Zone > my-app.com


// Important: instead of using `APIKey` use `APIToken` with no email-adress.
$key = new \Cloudflare\API\Auth\APIToken('<MY API_TOKEN GOES HERE>');
$adapter = new Cloudflare\API\Adapter\Guzzle($key);

// See https://janostlund.com/2019-10-07/purge-cloudflare-cache to find zone ID.
// Listing zones with APITokens seems to be broken.
$zoneID = 'abc1234567'; 
$dns = new \Cloudflare\API\Endpoints\DNS($adapter);
if ($dns->addRecord($zoneID, "A", 'testing', '8.8.8.8', 0, true) === true) {
    echo "DNS record created.". PHP_EOL;
}