Protecting files on your website from being accessed by unauthorized users can be very important. There are several methods by which you can accomplish this task. You could use PHP to listen for login authorization information on each page, or use a combination of .htaccess and .htpasswd to protect directories of your website. While the PHP approach would work fine i found the .htaccess solution to be the easier way to protect your files / directories from prying eyes.
The .htaccess file
To protect your chosen directory, you first have to create an .htaccess file. This is the file that the server will check before allowing access to anything in the directory the .htaccess file is in. In other words, the .htaccess file belongs in the directory you want to protect, and you can have one in each of as many directories as you like or need. First thing to do is to define some parameters in the .htaccess file. It needs to know where to find certain information, for example a list of valid usernames and passwords. Below is a sample of the few lines required in a .htaccess file.
AuthName "Please Log In"
The first line defines the location of the .htpasswd file. That file stores all the login credentials like user name and password. By the way, the passwords are stored encrypted (MD5). There is one important thing you should keep in mind when it comes to .htpasswd and its location:
The AuthName parameter defines the title of the password entry box when the user logs in. Technically you could skip that part but adding something meaningful as title of the password entry box makes sense, doesn’t it?. The AuthType tells the server what sort of processing is in use, and “Basic” is the most common one works for almost any purpose.
After adding the very basic information to the file your webserver now knows that it is supposed to protect that directory and where to look for a list of users that are allowed to access the directory and the files in it. The probably most common line you will need is
which basically tells the server that any user listed in .htpasswd is allowed to access the protected directory. If you would like to allow access to the directory for certain users only then you could specify those users by adding this line instead
require user dave
A complete .htaccess file could look like this
AuthName "Login to Habschned"