Created
January 10, 2016 00:26
-
-
Save theonlypwner/383374f784290ddede02 to your computer and use it in GitHub Desktop.
PHP IP Fix behind Reverse Proxies (CloudFlare and Varnish)
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 | |
// fix CloudFlare/Varnish IPs | |
function transform_cf(&$ip){ | |
if(!isset($_SERVER['HTTP_CF_CONNECTING_IP'])) | |
return; | |
$cf_cidrs = array( | |
"103.21.244.0/22", | |
"103.22.200.0/22", | |
"103.31.4.0/22", | |
"104.16.0.0/12", | |
"108.162.192.0/18", | |
"141.101.64.0/18", | |
"162.158.0.0/15", | |
"172.64.0.0/13", | |
"173.245.48.0/20", | |
"188.114.96.0/20", | |
"190.93.240.0/20", | |
"197.234.240.0/22", | |
"198.41.128.0/17", | |
"199.27.128.0/21", | |
// IPv6 not supported yet... | |
); | |
foreach($cf_cidrs as $cidr){ | |
list($subnet, $mask) = explode('/', $cidr); | |
// this works for IPv4, but not IPv6 | |
if (/*!$mask ||*/ ip2long($ip) >> $mask == ip2long($subnet) >> $mask){ | |
$ip = $_SERVER['HTTP_CF_CONNECTING_IP']; | |
return; // break; | |
} | |
} | |
// no change | |
} | |
function transform_varnish(&$ip){ | |
// Again, IPv6 doesn't work here... | |
$ipl = ip2long($ip); | |
if(!($ipl >> 24 == 10 || // 10.0.0.0/8 | |
$ipl >> 24 == 127 || // 127.0.0.0/8 | |
$ipl >> 20 == 0xAC1 || // 172.16.0.0/12 | |
$ipl >> 16 == 0xC0A8 // 192.168.0.0/16 | |
)) | |
return; | |
if(isset($_SERVER['HTTP_X_REMOTE_ADDR'])) | |
$ip = $_SERVER['HTTP_X_REMOTE_ADDR']; | |
elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) | |
$ip = explode(', ', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]; | |
// no change | |
} | |
transform_varnish($_SERVER['REMOTE_ADDR']); // local Varnish | |
transform_cf($_SERVER['REMOTE_ADDR']); // CloudFlare |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment