Denied access with pure PHP

Written by lexa on December 8, 2009 – 12:05 -

Often you have to protect a directory or website, so that not everybody has access to it. Besides, there are several possibilities as for example using .htaccess, but the best and quickest method as it seems to me is with PHP code.

You create a file with the name login.php, with following contents:

<?php

$user = "test";
$pw = "12345";

function authenticate () {
  Header("WWW-authenticate: basic realm=\"Restricted Area\"");
  Header("HTTP/1.0 401 Unauthorized");
  echo "Restricted Area!";
  exit;
}

if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] != $user || $_SERVER['PHP_AUTH_PW'] != $pw) {
  authenticate();
}
?>

Then you have to include the login.php to the top of index.php:

<?php
  include ("login.php");
?>

Thats all! It is important that there are no other index.* files in the directory.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • LinkedIn
  • Live
  • MisterWong
  • MisterWong.DE
  • Print
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yigg

Tags: , , , , ,
Posted in General, PHP | 1 Comment »

One Comment to “Denied access with pure PHP”

  1. simon Says:

    Thank you lexa, good article. Of course this kind of protection does not protect the entire content of the directory, but the ability to create listings of directories. So you will be able to download a resource by enteriring the correct URL into your browser. Still, this is very helpful for example for resource or graphics directories, especially if web server options can not be changed using .htaccess file.

Leave a Comment