PHP Password Protection

Learning how to use Password Protection with htaccess and htpasswd files can make it very easy to protect a large website, without modifying anything or playing with sessions. In this tutorial I’ll show you just how to do that, and how to easily add users to the htpasswd file.

htaccess

AuthName "Restricted Area" 
AuthType Basic 
AuthUserFile /home/username/hiddenfiles/.htpasswd
AuthGroupFile /dev/null 
require valid-user

This example .htaccess file should be placed within the folder you want protected. Notice the AuthUserFile – This should be the full path to your .htpasswd file, and it should be below your public_html folder so users cannot view it.

htpasswd Script

<?
$cryptedpw = crypt($password, substr(rand(), 0, 2));

$fp = fopen("/home/username/hiddenfiles/.htpasswd","a");
fwrite($fp, "$username:$cryptedpw\n");
fclose($fp);
?>

This script is pretty simple – it is just appending “username:encryptedpassword” to the .htpasswd file. Just remember to have the path the same as in the htaccess file, so it adds the users to the correct one.

To encrypt the password we just pass it through PHP’s crypt function, with a random 2 digit salt.