Skip to content


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[] = '211.109.238.74';
$ip[] = '254.254.254.2';
 
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;
}
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • E-mail this story to a friend!
  • Fark
  • Reddit
  • StumbleUpon

Profile:  Frank has been programming for the web using PHP, Javascript and numerous libraries and frameworks for the past 5 years. More articles.

Posted in PHP.

5 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Hi

    Thanks for this function. There is small bug in it. You are missing backslash in preg_replace.

    Should be like this:

    $ipregex = preg_replace(”/\./”, “\.”, $ip[$i]);
    $ipregex = preg_replace(”/\*/”, “.*”, $ipregex);

  2. Thanks, good spotting :)

  3. thank you. I was trying to make this on my own when I came across yours. Why do more work :) Very nice, short, and simple.

    du

  4. Thanks for the great PHP tip.

  5. Thanks for the function btw, its been really useful, one small tweak though….

    instead of
    ‘/’.$ipregex.’/’

    should be:
    ‘/^’.$ipregex.’/’

    Only because if an allowed IP was
    $ip[] = ”211.*.*.*”;

    it would also allow an IP of 74.192.211.23

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.