HomePHP Page 2 - User Authentication With Apache And PHP
Back To Basics - PHP
Want to restrict access to certain sections of your Web site?Or customize page content on the basis of user preferences? Or eventrack user movement across your site? Well, the bad news is that you'llneed to learn how to authenticate users on your site. The good news isthat this tutorial has everything you need to get started.
Now, there are a couple of different ways to go about adding this type of security to your application. The first (and most primitive, though also the simplest) is to simply have your Web server handle authentication for you. If you're using the Apache Web server (you probably are), you can access the server's authentication features to add basic security to your Web site.
In order to illustrate how this works, let's consider a simple example. Let's assume the existence of the following directory structure:
This tells the server that access to the "admin" directory
(the directory in which the ".htaccess" file is located) is to be controlled, and access is to be granted to users based on the username/password information in the file "/usr/local/apache/users"
The final step is to create the "users" file. Change to the "/usr/local/apache" directory (or whichever directory you've decided to store the user data in) and use the "htpasswd" command:
$ htpasswd -c users john
New password: ****
Re-type new password: ****
Adding password for user john
You can add more users to this file if you like (remember to
omit the "-c" parameter for all subsequent additions, as that parameter creates a brand-new, empty file).
Remember *not* to store the "users" file in a directory under the server document root, or else malicious users will be able to view and download the password database through a browser.
Now, attempt to access the "admin" directory via your Web browser. The browser should pop up a dialog box and prompt you for a username and password. Access to the "admin" directory will be granted only if you enter a correct username and password, as defined in the "users" file.