Restricting access to a directory using htaccess and generate a htpasswd file using php

htaccess:

first make a htaccess file with the following:

AuthType Basic

AuthName “Restricted Area”

AuthUserFile path/to/.htpasswd

require valid-user

Make sure there are no extra spaces after AuthUserFile, otherwise it won‘t work. The AuthUserFile is the path to the .htpsswd file we‘ll be creating next. Apache uses the mod_auth module for basic authentication. Keep in mind that the basic Authtype is quite vulnerable because it sends the passwords and logins unencrypted as plaintext and can hereby be captured by anyone listening in. The HTTP Digest Authentication on the other hand protects your password and login information whilst being transferred by including it in a message digest that has been hashed with MD5. 

htpasswd:

Now, we‘ll create a file called .htpasswd. The following lines are case-sensitive. The password has to be MD5‘d. Use a MD5 generator to do this. This is an example of a htpasswd file:

steven:5f4dcc3b5aa765d61d8327deb882cf99
seconduser:5f4dcc3b5aa765d61d8327deb882cf99

At the website of htaccessediter.com you can easily create htaccess files without any knowledge of apache or htaccess whatsoever.

I‘ve uploaded a php file which make it easier to generate a htpasswd file. It includes a form which allows you to insert multiple users and writes these in a htpasswd file. For safety reasons you should place the htpasswd outside of the document root, so it can‘t be accessed from the internet. All you need to do then is point your AuthUserfile from Apache to the right location. There are also two other files included. The authenticate file is a script that you have to include in php files that you want to secure with basic authentication. The authenticate file reads the user logins and md5‘d passwords from the htpasswd file and compares them to your submitted login and password. If you find an error or if you‘re having trouble getting it to work, just contact me at steven@webfizz.be

Download the files

Images

The form to fill in username and password for basic Authentication. The form writes the htpasswd file with the username and hashed password. The securepage.php file shows the basic authentication login dialog.

Leave a comment