SKYCUBE.net

Solutions for Go, MySQL, PHP, Linux and more

Restricetd access to a web-application with htaccess or php

Posted — Jul 3, 2009

If you building a simple web-application and you are not really sure, ow secure are the authentication and or the rest of the application you should think about to limit the access to the application.

Furthermore, may your application should be available only for testing purpose of several customers the following could help you:

First way using a .htaccess which controls the access using a apache web server.

This is a very fast solution BUT you CAN’T use hostnames and or full qualified dns names like skycube.net or yourname.dyndns.org

<Limit GET HEAD POST>
order deny,allow
allow from 62.75.185.219
allow from 127.0.1.1
allow from 127.0.0.1
deny from all
</Limit>

The second way which I prefer, using a php code snippet. This allows you to use hostnames and full qualified domain names. Definitely you can write it in less than the lines I used below for the code, but in of understanding what the code does, it’s better 😉

<?php
/**
 * ACL array
 */
$valid_hosts = array();
$valid_hosts[] = 'localhost';
$valid_hosts[] = '127.0.0.1';
$valid_hosts[] = '127.0.1.1';
$valid_hosts[] = 'yourname.dyndns.org';
$valid_hosts[] = 'skycube.net';

for($i=0;$i<sizeof($valid_hosts);$i++){
  $valid_ip = gethostbyname($valid_hosts[$i]);
  if($valid_ip == $_SERVER['REMOTE_ADDR']){
    $valid_state = 'valid';
    break;
  }
  else{
    $valid_state = 'invalid';
  }
}
if($valid_state != 'valid')
  header("Location: http://www.skycube.net");
?>