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;
}
Related posts:
No tags for this post.
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);
Thanks, good spotting
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
Thanks for the great PHP tip.