Changing Cloudflare Security Level Programmatically

Sometimes one of my sites is under attack from a click-fraud campaign. I needed to devise a way to detect such an attack and instantly and automatically change my Cloudflare security level from ‘medium’ to ‘under attack’. When in under-attack mode, Cloudflare performs additional browser checks to filter out robots. It doesn’t stop all the attacks, but it’s my duty to try something if options are available. To that end, here is a PHP snippet I use to change my site’s security level via a URI.

I use memcached here because another script polls the last security level that was set. This is optional. I decided to use the Herenow curl string because it is formatted like the Cloudflare API examples, and it just works. The common functions are:

The one tricky thing when dealing with Cloudflare is obtaining your zone ID for a given domain. With another API call we can retrieve the zone ID of a supplied domain like so:

Again, memcached is utilized to avoid over-polling Cloudflare for the zone ID. The same common functions are reused. Why this pattern? There are other Cloudflare convenience scripts I have made such as clearing cache or changing access rules. Also, when, say, v5 of the API eventually comes out, it is easy to change the curl string rather than having to modify custom PHP curl options.