Search code examples
phpblockcloudflare

How can i block all CloudFlare IPs in PHP


I have a problem with some proxy sites that are using cloudflare and they are cloaking and spamdexing my website.

How can i block all cloudflare ip's in php so these sites that are scraping my website get blocked .. or is there any better solution? My website is also using cloudflare.


Solution

  • luckily, cloudflare provides a list of their IP ranges here, so just check if the connecting IP is within 1 of those ranges, and exit() if it is.

    example implementation using the M6Web/Firewall:

    use M6Web\Component\Firewall\Firewall;
    
    if(!((new Firewall())->setDefaultState(true)->addList(file('blacklist.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES),'localBad')->setIpAddress($_SERVER['REMOTE_ADDR'])->handle())){
         http_response_code(403);
         exit();
    }
    

    with an accompanying daily cronjob:

    <?php
    $ips = file_get_contents ( 'https://www.cloudflare.com/ips-v4' ) . "\n" . file_get_contents ( 'https://www.cloudflare.com/ips-v6' );
    file_put_contents ( '/path/to/blacklist.txt', $ips );
    
    • note that it would be difficult to implement ipv6 cidr ranges manually, thus you should probably use a 3rd-party libary, like the M6Web firewall. also, it would be much more performant to do it with iptables than at the php level.

    • the cronjob is not really required, you can fetch a fresh list of ips with every pageload, but that would probably be very slow, and, perhaps ironically, you'd might get auto ip-banned from cloudflare.com for spamming, thus i highly suggest you use a daily cronjob.