Zend - The PHP Company




Security

Add Code


Check IP address matches or is in range  

Type: code fragment
Added by: studio24
Entered: 02/07/2003
Last modified: 07/12/2002
Rating: - (fewer than 3 votes)
Views: 9786
If you need to check if the current user's IP address is either within a set range or matches a given IP use this function. Possible uses include additional security for an authentication script. IP range needs to be in form 12.34.56.78-12.34.67.89


<?php
 
function checkIPorRange ($ip_address) {
    if (
ereg("-",$ip_address)) {  
        
// Range
        
$ar explode("-",$ip_address);
        
$your_long_ip ip2long($_SERVER["REMOTE_ADDR"]);
        if ( (
$your_long_ip >= ip2long($ar[0])) && ($your_long_ip <= ip2long($ar[1])) ) {
            return 
TRUE;
        }
    } else {
        
// Single IP
        
if ($_SERVER["REMOTE_ADDR"] == $ip_address) {
            return 
TRUE;
        }
    }
    return 
FALSE;
}
?>


Usage Example


$ip_range = "198.152.0.0-198.152.4.0";

if (checkIPorRange($ip_range)) {
    print "IP OK";
}
If your IP was 198.152.1.32
The above would return: IP OK


Rate This Script





Search



This Category All Categories