Tuesday, July 6, 2010

HTTP Basic Authentication with PHP Session

Today my challenge is to protect HTML files using PHP Session detection. Here is my case. We have a Wiki system, so our clients can login the Wiki to read all documents written on the Wiki system. We also have API documentation which are generated by PHPDoc automatically and in HTML format. We don't want the client to login again using HTTP Basic Authentication pop-up window. In other words, we would like the single sign-on (SSO) for our clients to read all documentations in different systems.

Once clients login, there is Wiki session is available for authenticating apache protected HTML folders. Here is how I did.

1. Turn on Apache .htaccess check by setting the following line in httpd.conf.

AllowOverride All

For instance,

<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>

Then, restart Apache.

2. Create a .htaccess under a folder where HTML files are located and are required to be protected, and add the following handler:

AddHandler mywrapper .html
Action mywrapper /authenticate.php


3. Create an authenticate.php file under the web root with the following content:

<?php
session_start();
$url = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['REQUEST_URI'];
if(!strstr($url, ".html")) $url.= "index.html";
if($_SESSION['username']) {
include($url);
exit();
} else {
echo 'Please login first. <a href="#">Login</a>';
die();
}
?>


If you get PHP error on the above code as following:

PHP Parse error: syntax error, unexpected T_STRING

You may change include($url); to readfile($url);

That is all. It is a simple solution for HTTP Basic Authentication using PHP Session.

No comments:

Post a Comment