How to use .htaccess/.htpasswd Password Protection with PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to use .htaccess/.htpasswd Password Protection with PHP

Post by Tony » Sun Nov 29, 2009 5:20 am

Setting up password protection
The best way to secure content on your website is to use .htaccess/.htpasswd protection. This will password protect any directory and all directories below. You will need to create a .htaccess file which you put in the directory you want to protect. You will also need to create a .htpasswd file which you will put out of reach (see tip on Securing Your Package). The .htaccess file should contain the following:

Code: Select all

AuthUserFile /full_unix_path_to_your_file/.htpasswd
AuthName "Any Name You Want"
AuthType Basic
require user username 
Where username is the name of the user specified in the .htpasswd file.
You can also make that last line

Code: Select all

require valid-user 
to accept any user specified in the .htpasswd file.

You can also limit the password protection. For example put the .htaccess code inside these tags

Code: Select all

<files file.ext>
htaccess protection code goes here

Code: Select all

</files>
to limit the password protection to just the file "file.ext".

The .htpasswd file should genrally be put at your ftp root (above the public directory). It is in the form:

Code: Select all

user:encrypted password 
The best way to create these files is using notepad (for example create htaccess.txt in notepad), then upload, then rename on the server (.htaccess).
You can encrypt the password using the form in B&T's Tool Box (on this page) or use your own script (also available on this page).
More information can be found on this technique in the Apache documentation here.

Encrypt your password for .htpasswd

Want your own script that you can use to make the encrypted password lines for your .htpasswd file? Use this one.

Code: Select all

<?php
if (!empty($_POST[password]) AND !empty($_POST[user])) {
  $user = $_POST[user]; 
  $password = $_POST[password]; 
  $encryptedPassword = crypt($password);
}
$script = $_SERVER['SCRIPT_NAME'];
echo "<html><head><title>Password Encryption</title></head><body>
<form method=post action='$script'>
<font size=5><b>.htpasswd File Password Encryption</b></font>
<br><br>Enter Username<br>
<input name=user value='$user' size=20>
<br><br>Enter Password<br>
<input name=password value='$password' size=20>
<br><br><input type=submit name=submit value='Encrypt Now'>
";
if (!empty($user) AND !empty($encryptedPassword)) {
  echo "<br><br>.htpasswd File Code<br>$user:$encryptedPassword";
}
echo "</form></body></html>";
?>
Auto Password Change and Email Notification

This script will change your .htpasswd password to a new random password (with encryption) and send an email to notify you of the change. You can run this script automatically using cron at what ever interval you like, or run it manually.

Code: Select all

<?php
$filename = "/XXXXXX/.htpasswd";  // the location of your .htpasswd file
$username = "XXXXXXX"; // the username specified in the .htaccess file
$length = "10"; // length of the password
$emailaddress = "[email protected]"; // email address
// change nothing below this line
// generate password
$spec_charset = array("!","@","#","$","%","^","&","*","_","+"."?","=");
$chars = array();
unset($pass);
for ($i = 1; $i <= $length; $i++) {
  for ($i = 48; $i <= 57;   $i++) $chars[] = chr($i); // numbers
  for ($i = 65; $i <= 90;   $i++) $chars[] = chr($i); // upper
  for ($i = 97; $i <= 122; $i++)  $chars[] = chr($i); // lower
  foreach ($spec_charset as $i)   $chars[] = $i;      // special
  for ($i = 1; $i <= $length; $i++) $pass .= $chars[rand(0,count($chars)-1)];  
}
// build & write .htpasswd file
$encrypted = crypt($pass);
$output = "$username:$encrypted\n";
if (file_put_contents($filename,$output))
  $message = "Your password has been changed to $pass";
else
  $message = "There was an error creating your new password";
// send notification
mail($emailaddress,"Password Notification",$message,"From: Website <>");
?>
Auto generate .htpasswd file

This php script reads a MySQL database, encrypts the passwords and writes an htpasswd file. Using this script you can maintain a database of users and generate an .htpasswd file from the database.

Code: Select all

<?php
$filename = "your htpasswd file path goes here";  // your htpasswd file name - complete unix path - or relative to this script
$host="host";     // database host address
$dbuser="user";                    // database user name
$dbpswd="password";             // database password
$mysqldb="db_name";             // name of database
$table="passwd_table";          // name of table
// modify the above lines for your environment
mysql_connect("$host", "$dbuser", "$dbpswd");
mysql_select_db ("$mysqldb");
$query = mysql_query("SELECT * FROM $table");
while ($row = mysql_fetch_array($query)) {
  $user = $row['user'];
  $pass = $row['password'];
  $encrypted = crypt($pass);
  $record .= "$user:$encrypted\r\n";
}
file_put_contents($filename,$record);
?>
Passing user authentication information to PHP

The best way to protect your directory is with htaccess/htpasswd protection. But you may also want to pass the user information to your php scripts so you can do custom processing based on who logged in. You can retrieve the current authenticated user with one php line. Put this in the target script in the protected directory (used in the script after authentication).

Code: Select all

<?php 
$user = $_SERVER['REMOTE_USER']; 
?>
Post Reply

Return to “PHP & MySQL”