Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
Project "PHP Folder Password Authentication"
Purpose
The purpose of this project is to show you how to accept a web form POST submission in order to require password protection on folders in a website.

Project Details
On Linux/Apache web servers, it is quite simple to set up password protection on folders of a website through the use of .htaccess and .htpasswd files. Unfortunately, Windows and IIS do not exhibit the same, easy capability so even if PHP is running on a Windows server the same use of .htaccess and .htpasswd is not handled unless you have some type of ISAPI mod in place. Update: Actually, I was able to find a IIS 7 Apache emulator module for Windows Server 2008/Windows 7 called Ape.

By default, when a resource is requested, the existence of the .htaccess file is checked (either at the root website level or top-most folder level that the resource is located within). If one is found then directives contained in that .htaccess file are followed by the web server. While there are many things that may be done with an .htaccess file, in this context we merely use it to indicate password protection is used by pointing to the location of the .htpasswd file in conjunction with specifying an authentication requirement. While many websites will place the location of the .htpasswd file (contains clear text logon and encrypted password) outside of the folder authentication is required for, additional parameters are specified in the .htaccess folder telling the web server that neither .htaccess or .htpasswd may be accessed over http or https. This directive prevents users from being able to type in a URL directly to either file to be able to get to them. This allows us to place the .htaccess and .htpasswd files in the same folder without worrying about them being accessible by a URL request.

Of course, depending on your security requirements, you may or may not place the .htpasswd file in the same folder where authentication is required. This is really up to you. If someone is able to gain access to either the .htaccess or .htpasswd file on the web server it will likely mean you have a larger security vulnerability...so where those files may reside would pose little security value.

The Code
As indicated previously, setting up logon and password authentication with PHP is as simple as having the .htaccess and .htpasswd files setup on the website. In the context of this tutorial, you simply provide the name of the folder you wish to have password protected (or to have a logon/password added to) and it takes care of the rest. The variable $partial_path indicates the parent folder that all of password protected folders will be contained within.

<?php
		    global $partial_path, $username, $userpassword, $directory, $prompt_title;

		    // Basic Customization
		    $partial_path = "/folder_containing_password_protected_folders";
		    $prompt_title = "Client Authentication";

		    // Read Data From Form Submission
		    $directory = $_POST[directory];
		    $username = str_replace(" ", "", $_POST[username]);
		    $userpassword = str_replace(" ", "", $_POST[userpassword]);

		    // Create .htaccess and .htpasswd in $directory specified in Form Submission
		    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $partial_path . "/" . $directory;
		    $filename = $targetPath . "/" . ".htaccess";
		    if (file_exists($filename)) {
						 // Do Nothing
						}
		    else {
			  // Create .htaccess to require authentication for the folder specified.
			  // Prevent .htaccess and .htpasswd from being accessible over http or https.
			  $Handle = fopen($filename, 'w');
			  $Data = "AuthUserFile " . $_SERVER['DOCUMENT_ROOT'] . $partial_path . "/" . $directory . "/.htpasswd\n";
			  $Data = $Data . "AuthGroupFile /dev/null\n";
			  $Data = $Data . "AuthName \"" . $prompt_title . "\"\n";
			  $Data = $Data . "AuthType Basic\n";
			  $Data = $Data . "<Limit GET POST>\n";
			  $Data = $Data . "require valid-user\n";
			  $Data = $Data . "</Limit>\n";
			  $Data = $Data . "<files .htaccess>\n";
			  $Data = $Data . "Order allow,deny\n";
			  $Data = $Data . "Deny from all\n";
			  $Data = $Data . "</files>\n";
			  $Data = $Data . "<files .htpasswd>\n";
			  $Data = $Data . "Order allow,deny\n";
			  $Data = $Data . "Deny from all\n";
			  $Data = $Data . "</files>\n";
			  fwrite($Handle, $Data);
			  fclose($Handle);
			 }
		    $filename = $targetPath . "/" . ".htpasswd";
		    if (file_exists($filename)) {
						 // Add logon and encrypted password
						 $Data = $username . ":" . crypt(trim($userpassword),base64_encode(CRYPT_STD_DES)) . "\n";
						 file_put_contents($filename, $Data, FILE_APPEND);
						}
		    else {
			  // Create logon and encrypted password
			  $Handle = fopen($filename, 'w');
			  $Data = $username . ":" . crypt(trim($userpassword),base64_encode(CRYPT_STD_DES)) . "\n";
			  fwrite($Handle, $Data);
			  fclose($Handle);
			 }
?>


PHP on Windows
If you have trouble running PHP on a Windows web server (when PHP is installed), adding the code below to the top of the PHP page (just below the opening <?php) may assist in allowing it to run by defining "$_SERVER['DOCUMENT_ROOT']".

if(!isset($_SERVER['DOCUMENT_ROOT'])) {
				       if(isset($_SERVER['SCRIPT_FILENAME'])) {
									       $_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF'])));
									      }
				      }
if(!isset($_SERVER['DOCUMENT_ROOT'])) {
				       if(isset($_SERVER['PATH_TRANSLATED'])) {
									       $_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr(str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']), 0, 0-strlen($_SERVER['PHP_SELF'])));
									      }
				      }
About Joe
Find Out Now!