Friday, May 8, 2009

Restricting user access based on IP Address


We can restrict access to webpages based on IP address of the user's computer.
In php, we can get ipaddress of the user' computer using REMOTE_ADDR as below.

$client_ipaddress=trim($_SERVER['REMOTE_ADDR']);

It will get the ipaddress in the ipv4 format (e.g 192.168.1.1).

Searching the database table using this format is very difficult and not efficient in terms of performance.

So, we can convert the ipaddress from this format to a numeric/integer value using below function.


$client_ipaddress_num=ip_address_to_number($client_ipaddress); //convert the
ipaddress from x.x.x.x formt to number



function ip_address_to_number($IPaddress)
{
//Converting IP address in x.x.x.x format into numeric values
if ($IPaddress =="")
{
return 0;
}
else
{
$ips = explode('.', $IPaddress);
return ($ips[3] + $ips[2] * 256 + $ips[1] * 65536 + $ips[0] * 16777216);
}

}

Once after converting the ipaddress into numeric form, we can easily verify whether the user's ip is valid (i-e exists between pre-stored range of ips.) using query similar to below one.


$query="select userid from ip_lookup_table where minip_num <=".$client_ipaddress_num." and maxip_num>=".$client_ipaddress_num;

Note that REMOTE_ADDR will return the ip address assigned by the ISP only, it won't return the internal ip of LAN connected to ISP.

More Articles...

No comments:

Search This Blog