views:

324

answers:

2

I have a PHP page I need to limit execution access of to only clients inside our firewall.

How would I write a php-script that can look up the clients ip-address and match it to a ip-range (for instance 10...* or 200.10.10.*).

+3  A: 

Well, assuming you're using Apache, there's a module called mod_authz_host that you can use.

Together with the file directive, you could limit access to a given php script for a range of ip addresses.

Here is the link to the documentation on that module: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html

Here's a quick example (assuming your php file is called admin.php):

<file admin.php>
  Order Deny,Allow
  Deny from all
  Allow from 200.10.10
</file>

The added benefit to the other solution suggested here is that you can control the security aspects from outside your application logic - a more flexible approach that does not impose any limitations on your PHP code.

Lior Cohen
+1 for fixing this in the server config / .htaccess file rather than in PHP (if the OP has access)
Cheekysoft
I like this solution too. I guess I also could make a complete virtualhost or directory protected.I didn't make solution in php though.
Johan Carlsson
+2  A: 

You can use ip2long to convert dotted quads to long values, then just perform some arithmetic to check a given network/mask combination:

$network=ip2long("200.10.10.0");
$mask=ip2long("255.255.255.0");

$remote=ip2long($_SERVER['REMOTE_ADDR']);

if (($remote & $mask) == $network)
{
   //match!
}
else
{
   //does not match!
}
Paul Dixon
+1 This is a much better solution then then one I came up with. Thanks!
Johan Carlsson