This is for longhand or shorthand subnet masks.
Code:
function checkIPAddress($ipAddressCheck, $networkAddress, $subnetMask)
{
$shorthandSubnet=convertSubnetToShorthand($subnetMask); //Remove this line if you want $subnetMask to take shorthand subnet inputs (eg $subnetMask="8"; for /8 (255.0.0.0)
$subnetBin=(pow(2,32)-1)-(pow(2,32-$shorthandSubnet)-1);
$firstIP=ip2long($networkAddress) & ($subnetBin);
$NetworkLength=pow(2,32-$shorthandSubnet)-1;
$longIPAddressCheck = ip2long($ipAddressCheck);
if ($longIPAddressCheck > $firstIP && $longIPAddressCheck < ($firstIP + $NetworkLength))
{
return "true";
}
else
{
return "false";
}
}
function convertSubnetToShorthand($subnetMask)
{
$subnetOctets=explode(".", $subnetMask, 4);
$reconcatinateSubnetMaskCount="";
for ($octetIndex = 0; $octetIndex <= 3; $octetIndex++)
{
$subnetBinaryIndex[$octetIndex]=decbin($subnetOctets[$octetIndex]);
$reconcatinateSubnetMaskCount=$reconcatinateSubnetMaskCount . $subnetBinaryIndex[$octetIndex];
}
return substr_count($reconcatinateSubnetMaskCount, "1");
}