[PHP] Block Bots with CloudFlare

XARON

get over here!
Restricted
Nov 24, 2016
162
161
118
Hello everyone, i I'd like to share with you this class i developed a long time ago to protect from bots. I'll keep developing if you like :)

PHP:
<?php

class CloudFirewall {

    private $email;
    private $key;
    private $curl;

    public function __construct($email, $key) {
        $this->email = $email;
        $this->key = $key;
    }

    public function changeSecurityLevel($zone, $value = 'low'){
        if (!$this->checkSecurityLevel($value)):
            return false;
        elseif(empty($zone)):
            return false;
        else:
            return $this->connect('https://api.cloudflare.com/client/v4/zones/'.$zone.'/settings/security_level', 'PATCH', array('value' => $value));
        endif;
    }

    public function blockIPv4($value){
        if(!$this->checkIPv4($value)):
            return false;
        else:
            return $this->connect('https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules', 'POST', array('mode' => 'block', 'configuration' => array('target' => 'ip', 'value' => $value), 'notes' => 'Blocked by CloudFirewall'));
        endif;
    }

    protected function connect($url, $request, $fields){
        $this->curl = curl_init();
        curl_setopt($this->curl, CURLOPT_URL, $url);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
        if($request == 'POST'){
            curl_setopt($this->curl, CURLOPT_POST, 1);
        }else{
            curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $request);
        }
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, json_encode($fields));
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('X-Auth-Email: '.$this->email, 'X-Auth-Key: '.$this->key, 'Content-Type: application/json'));
        return curl_exec($this->curl);
        curl_close($this->curl);
    }

    protected function checkSecurityLevel($value){
        if (in_array($value, array('essentially_off', 'low', 'medium', 'high', 'under_attack'))):
            return true;
        else:
            return false;
        endif;
    }

    protected function checkIPv4($value){
        if(filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)):
            return true;
        else:
            return false;
        endif;
    }

}


$firewall = new CloudFirewall('YOUR_CF_EMAIL', 'YOUR_CF_GLOBAL_KEY');
$firewall->changeSecurityLevel('YOUR_CF_ZONE_ID', 'medium');
$firewall->blockIPv4('31.13.37.31');
 

B0STANLI

BrownStarTeam
Oct 20, 2015
11
17
38
If it's suitable for the new CloudFlare API release, it's a really important issue.
 
Top