Created
July 5, 2022 08:02
-
-
Save JBlond/d4022730ab003e7d1fd7dfe87456bd39 to your computer and use it in GitHub Desktop.
change IP if it is coming from cloudflare
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Cloudflare IP Reset | |
//See if ip fits in IP range | |
function ip_in_network($ip, $net_addr, $net_mask){ | |
if($net_mask <= 0){ return false; } | |
$ip_binary_string = sprintf("%032b",ip2long($ip)); | |
$net_binary_string = sprintf("%032b",ip2long($net_addr)); | |
return (substr_compare($ip_binary_string,$net_binary_string,0,$net_mask) === 0); | |
} | |
//See if the "Cloudflare IP" is really a cloudflare IP | |
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) { | |
$ishost = 0; $iscloudflare = 0; | |
$cloudflare_ips = array ( //Cloudflare Owned IP Ranges | |
'1' => array( | |
'ip' => '103.21.244.0', | |
'range' => '22' | |
), | |
'2' => array( | |
'ip' => '103.22.200.0', | |
'range' => '22' | |
), | |
'3' => array( | |
'ip' => '103.31.4.0', | |
'range' => '22' | |
), | |
'4' => array( | |
'ip' => '104.16.0.0', | |
'range' => '12' | |
), | |
'5' => array( | |
'ip' => '108.162.192.0', | |
'range' => '18' | |
), | |
'6' => array( | |
'ip' => '141.101.64.0', | |
'range' => '18' | |
), | |
'7' => array( | |
'ip' => '162.158.0.0', | |
'range' => '15' | |
), | |
'8' => array( | |
'ip' => '172.64.0.0', | |
'range' => '13' | |
), | |
'9' => array( | |
'ip' => '173.245.48.0', | |
'range' => '20' | |
), | |
'10' => array( | |
'ip' => '188.114.96.0', | |
'range' => '20' | |
), | |
'11' => array( | |
'ip' => '190.93.240.0', | |
'range' => '20' | |
), | |
'12' => array( | |
'ip' => '197.234.240.0', | |
'range' => '22' | |
), | |
'13' => array( | |
'ip' => '198.41.128.0', | |
'range' => '17' | |
), | |
'14' => array( | |
'ip' => '199.27.128.0', | |
'range' => '21' | |
), | |
); | |
$cur_ip = 1; | |
$num_ip = count($cloudflare_ips); | |
while ($cur_ip < $num_ip) { | |
if (ip_in_network($_SERVER['REMOTE_ADDR'],$cloudflare_ips[$cur_ip]['ip'],$cloudflare_ips[$cur_ip]['range'])) {$iscloudflare = 1;} //If IP matches any of cloudflare's | |
$cur_ip = ++$cur_ip; | |
} | |
if ($_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR']) {$ishost = 1;} //If IP matches your servers | |
if ($iscloudflare || $ishost) { | |
//If IP is really a cloudflare IP or host IP, then it's good to convert to the real user's IP | |
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment