SEO, PHP and Javascript Web Dev

Search Engine Optimisation, Web Development and Network Administration Ramblings

-->
03 2007

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 this Post:
  • Reddit
  • Sphinn
  • del.icio.us
  • Digg
  • e-mail
  • Mixx
  • Google
  • StumbleUpon

Related posts:

  1. Tip of the Week : CakePHP redirect to admin methods
  2. Multiple File Uploads CakePHP jQuery
  3. CakePHP paginator for multiple sets of data on one page using AJAX
  4. Tip of the Week : Running cUrl on localhost can topple your router
  5. Tip of the Week : Carriage Returns in PHP Plain Text Emails

No tags for this post.
« Mapping Client Network Printers
more… is less duplicate content on wordpress »

4 Responses to “Restict Logins by IP Address”

  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.

Leave a Reply

-->
  • Photography