I run security checks on a number of AJAX calls to see if the same IP requested that I have on record.
I used the following set of class functions to establish the IP (which can come via load balancers, hence the lengthly methodology.
private function IPMask_Match ($network, $ip) {
$ip_arr = explode('/', $network);
if (count($ip_arr) < 2) {
$ip_arr = array($ip_arr[0], null);
}
$network_long = ip2long($ip_arr[0]);
$x = ip2long($ip_arr[1]);
$mask = long2ip($x) == $ip_arr[1] ? $x : 0xffffffff << (32 - $ip_arr[1]);
$ip_long = ip2long($ip);
return ($ip_long & $mask) == ($network_long & $mask);
}
private function IPCheck_RFC1918 ($IP) {
$PrivateIP = false;
if (!$PrivateIP) {
$PrivateIP = $this->IPMask_Match('127.0.0.0/8', $IP);
}
if (!$PrivateIP) {
$PrivateIP = $this->IPMask_Match('10.0.0.0/8', $IP);
}
if (!$PrivateIP) {
$PrivateIP = $this->IPMask_Match('172.16.0.0/12', $IP);
}
if (!$PrivateIP) {
$PrivateIP = $this->IPMask_Match('192.168.0.0/16', $IP);
}
return $PrivateIP;
}
public function getIP () {
$UsesProxy = (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) || !empty($_SERVER['HTTP_CLIENT_IP'])) ? true : false;
if ($UsesProxy && !empty($_SERVER['HTTP_CLIENT_IP'])) {
$UserIP = $_SERVER['HTTP_CLIENT_IP'];
}
elseif ($UsesProxy && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$UserIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
if (strstr($UserIP, ',')) {
$UserIPArray = explode(',', $UserIP);
foreach ($UserIPArray as $IPtoCheck) {
if (!$this->IPCheck_RFC1918($IPtoCheck)) {
$UserIP = $IPtoCheck;
break;
}
}
if ($UserIP == $_SERVER['HTTP_X_FORWARDED_FOR']) {
$UserIP = $_SERVER['REMOTE_ADDR'];
}
}
}
else{
$UserIP = $_SERVER['REMOTE_ADDR'];
}
return $UserIP;
}
The Problem is I've been getting problems with users operating via a proxy. Can anyone indicate why that might be? I've used basic free proxy's online to try and emulate, but it doesn't look to be getting variable IPs or anything - so I'm not sure why this would be saying the two IPs don't match.