Tero

[+] Check if the request is from CloudFlare

Nov 1st, 2016
770
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.29 KB | None | 0 0
  1. <?php
  2. /**
  3. + Info: This script should help you out to check if the request is from CloudFlare and not directly though a ip address.
  4. **/
  5.  
  6. function ip_in_range($ip, $range) {
  7.     if (strpos($range, '/') == false)
  8.         $range .= '/32';
  9.  
  10. # [+] $range is in IP/CIDR format eg 127.0.0.1/24
  11.    list($range, $netmask) = explode('/', $range, 2);
  12.     $range_decimal = ip2long($range);
  13.     $ip_decimal = ip2long($ip);
  14.     $wildcard_decimal = pow(2, (32 - $netmask)) - 1;
  15.     $netmask_decimal = ~ $wildcard_decimal;
  16.     return (($ip_decimal & $netmask_decimal) == ($range_decimal & $netmask_decimal));
  17. }
  18.  
  19. # [+] IP Ranges - 01.11.2016 / Url: https://www.cloudflare.com/ips-v4
  20. function _cloudflare_CheckIP($ip) {
  21.     $cf_ips = array(
  22.         '103.21.244.0/22',
  23.         '103.22.200.0/22',
  24.         '103.31.4.0/22',
  25.         '104.16.0.0/12',
  26.         '108.162.192.0/18',
  27.         '131.0.72.0/22',
  28.         '141.101.64.0/18',
  29.         '162.158.0.0/15',
  30.         '172.64.0.0/13',
  31.         '173.245.48.0/20',
  32.         '188.114.96.0/20',
  33.         '190.93.240.0/20',
  34.         '197.234.240.0/22',
  35.         '198.41.128.0/17',
  36.         '199.27.128.0/21'
  37.       );
  38.  
  39.     $is_cf_ip = false;
  40.     foreach ($cf_ips as $cf_ip) {
  41.         if (ip_in_range($ip, $cf_ip)) {
  42.             $is_cf_ip = true;
  43.             break;
  44.         }
  45.     } return $is_cf_ip;
  46. }
  47.  
  48. function _cloudflare_Requests_Check() {
  49.     $flag = true;
  50.     if(!isset($_SERVER['HTTP_CF_CONNECTING_IP']))   $flag = false;
  51.     if(!isset($_SERVER['HTTP_CF_IPCOUNTRY']))       $flag = false;
  52.     if(!isset($_SERVER['HTTP_CF_RAY']))             $flag = false;
  53.     if(!isset($_SERVER['HTTP_CF_VISITOR']))         $flag = false;
  54.     return $flag;
  55. }
  56.  
  57. function isCloudflare() {
  58.     $ipCheck        = _cloudflare_CheckIP($_SERVER['REMOTE_ADDR']);
  59.     $requestCheck   = _cloudflare_Requests_Check();
  60.     return ($ipCheck && $requestCheck);
  61. }
  62.  
  63. # [+] Use when handling ip's
  64. function getRequestIP() {
  65.     $check = isCloudflare();
  66.     if($check) {
  67.         return $_SERVER['HTTP_CF_CONNECTING_IP'];
  68.     } else {
  69.         return $_SERVER['REMOTE_ADDR'];
  70.     }
  71. }
  72.  
  73. # [+] To use the script it's quite simple
  74. $ip = getRequestIP();
  75. $cf = isCloudflare();
  76.  
  77. if($cf) echo "CloudFlare Detected<br/>";
  78. else    echo "Not CloudFlare";
  79.  
  80. echo "Your actual ip address is: ".$ip;
  81. ?>
Advertisement
Add Comment
Please, Sign In to add comment