Password Protection with .htaccess and .htpasswd
Here you can encrypt passwords for use with password protection with .htaccess and .htpasswd. This functionality is standard on the Apache webserver and works in all normal browsers. Encrypting passwords means they are not send or stored in clear text.
Enter username and password to encrypt the password and get the resultant line to enter in your .htpasswd file. One line for each user.
Encrypt password for .htpasswd
Usernames and passwords entered here are not stored, not disclosed to third party, or used in any other way than to provide this service.
Example line in a .htpasswd file with the username "userdude" and password "password":
The PHP code encrypting the password:
Encryption source code
<?php echo crypt('password', base64_encode('password')); ?>
How to Setup
Attention: the files must be named as
.htpasswd. Files prefixed with
.ht will by default not be send to clients by the Apache webserver and if somebody makes a request they will get an error 403 Forbidden.
The htaccess file must contain the following lines and be placed in the folder with the content to protect:
The above will protect an entire folder, if only specific files should be protected replace the line
require valid-user with:
It's possible to add multiple entries and add multiple users to an entry.
require user user01 user02 ...
Path to AuthUserFile
For the system to work the correct path to .htpasswd must be set on the
AuthUserFile line in .htaccess. The absolute path to the file on the server must be used and to obtain this you can upload a file to the directory where you're going to store .htpasswd (can be deleted again after use):
<?php echo __DIR__.DIRECTORY_SEPARATOR.'.htpasswd'; ?>
The ouput will be something like:
And in .htaccess it will then be:
An example folder structure could be:
Folder structure example
mysite/ ├── inc/ │ └── .htpasswd ├── admin/ │ ├── .htaccess │ ├── file01.php │ └── file02.jpg
When the setup is in place users will be prompted to enter credentials when requesting the pages and files specified.
This page could also be of interest: HTTP authentication with PHP.