Skip to content

Instantly share code, notes, and snippets.

@kevinpareek
Last active April 7, 2020 13:02
Show Gist options
  • Save kevinpareek/44d5ab75c4e9449877815771cd97f161 to your computer and use it in GitHub Desktop.
Save kevinpareek/44d5ab75c4e9449877815771cd97f161 to your computer and use it in GitHub Desktop.
Block / unBlock IPs in firewall via Cloudflare V4 PHP API
<?php
/**
* @ author https://www.kevinpareek.com
* @ Tuesday, 7 April 2020
**/
class cf_ipBan
{
private $cfEmail;
private $apiKey;
public function __construct($cfEmail,$apiKey){
$this->cfEmail = $cfEmail;
$this->apiKey = $apiKey;
}
public function ipBan($ipaddr,$by=false){
$cfheaders = array(
'Content-Type: application/json',
'X-Auth-Email: '.$this->cfEmail.'',
'X-Auth-Key: '.$this->apiKey.''
);
$by = $by===false ? 'Kevin\'s cf_ipBan Library' : $by;
$data = array('mode' => 'block', 'configuration' => array('target' => 'ip', 'value' => $ipaddr), 'notes' => 'Banned on '.date('d-m-Y H:i:s').' by '.$by);
$json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $cfheaders);
curl_setopt($ch, CURLOPT_URL, 'https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules');
$return = curl_exec($ch);
curl_close($ch);
return $return;
}
public function ipUnBan($block_rule_id){
$cfheaders = array(
'Content-Type: application/json',
'X-Auth-Email: '.$this->cfEmail.'',
'X-Auth-Key: '.$this->apiKey.''
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $cfheaders);
curl_setopt($ch, CURLOPT_URL, 'https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules/'.$block_rule_id);
$return = curl_exec($ch);
curl_close($ch);
return $return;
}
}
$cloudflare_email = ''; // your cloudflare account email
$apiKey = ''; //your cloudflare account apiKey
$ip = '';
$cf = new cloudflare_ip_ban($cloudflare_email, $apiKey);
$ipBan = $cf->cloudflare_ipBan($ip);
echo '<pre>';
print_r($ipBan);
@umeshdepale
Copy link

helpfull code

@kevinpareek
Copy link
Author

helpfull code

thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment