Our goal during this "mini tutorial" is to set up a system that secures your site with an easy to use authentication mechanism.
At the top of the site to secure, place the following code snippet:
Example 34-1. Typical usage example for PEAR::Auth
This few lines of code instantiate the authentication system.
The first line in the above script includes the file from your PEAR directory. It contains all the necessary code to run PEAR::Auth. Next, we define a function to display the login form which the visitor of your page has to use to enter his login data. You can change all the HTML formatting in this function.
Since we want to use a database to verify the login data, we now create the variable $dsn, it contains a valid DSN string that will be used to connect to the database via PEAR::DB. For the default database table schema or to use a different storage container, please see below for more information.
After that we create the authentication object. The first parameter defines the name of the storage container. Because we want to use a database driven storage container, we pass "DB" here. The second parameter is the connection parameter for the container driver. We use the previously defined DSN string. The third parameter is the name of our function that we defined at the beginning of the script. It prints the login form.
Now our authentication object is initialized and we need to check if the user is logged in. This is done via the method checkAuth(). If it returns TRUE, we can pass the content of our page to the user.
Example 34-2. Using optional authentication
This is a pretty nice example for the optional login feature: The last parameter $optional can be either TRUE or FALSE. If it is FALSE, the login form is not shown and the user only sees the text "Everybody can see this text!". If he clicks on the link above this text, he gets the same page but with the GET parameter "login=1". Now he can enter his login information in the login form. If he successfully logs in, he can then see the text "Everybody can see this text!" and the text "One can only see this if he is logged in!".
Example 34-3. Logout functionality
The following example performs a "logout" for the current user and displays the login form again.
In the following passages we cover more detailed information about the functions of PEAR::Auth.
This SQL statement creates a table usable under the default database authentication scheme using MySQL:
CREATE TABLE auth ( username VARCHAR(50) default '' NOT NULL, password VARCHAR(32) default '' NOT NULL, PRIMARY KEY (username), KEY (password) );
These are the table and field names necessary for working authentication. When hashing the passwords with the MD5 algorithm, which is the default encryption method in PEAR::Auth, the password column must be at least 32 characters long. When using another encryption method like DES ("UNIX crypt"), the column size has to be changed correspondingly.