Restict Logins by IP Address

Today I had to write into an admin area on one of our sites a restriction so that only people at certain IP addresses could log in.

I wrote a pretty quick piece of code, but it seems to work nicely enough so I though I would convert it into a quick and dirty php function and put it out there...

This system works very simply by reading IP addresses in an array. It converts them to a basic regex by escaping periods with \. and matching against the current IP address in $_SERVER[REMOTE_ADDR]. I also allow IP ranges in a way that I think is kind of cunning.

As you would ordinarily write an IP address range as: 10.10.3.* - all I do is replace any *'s with .*'s and then that works in the preg_match() function too.

I haven't tested the function, but it should return true if there is a match and false if there is not - let me know if you come across any errors in it :).

//allowable IP addresses for admin login.
$ip = array();
$ip[] = '10.10.3.*';
$ip[] = '';
$ip[] = '';
function testIP($ip){
//testing that correct IP address used in order
//to access admin area...
for($i=0, $cnt=count($ip); $i<$cnt; $i++) {
    $ipregex = preg_replace("/./", "\.", $ip[$i]);
    $ipregex = preg_replace("/*/", ".*", $ipregex);
    if(preg_match('/^'.$ipregex.'/', $_SERVER[REMOTE_ADDR]))
        return true;
    return false;