- Remembering the Basics
- Validating Form Data
- Using PECL Filter
- Authentication with PEAR Auth
- Using MCrypt
Authentication with PEAR Auth
One of the more common elements in today's Web sites is an authentication system: users register with a site, they log in to gain access to some parts, and restricted pages allow or deny access accordingly. Such systems aren't hard to implement—I've done so in some of my other books—but here I'd like to look at what PEAR has to offer.
The PEAR Auth package provides a really easy, yet customizable authentication system. To show it off, I'll start with one very simple example. This will mostly demonstrate its basic usage. Then I'll show how to customize the authentication system to fit it into a larger application. For both examples, you'll need to install the PEAR Auth package. Because the authentication information is stored in a database, the PEAR DB package must also be installed. If you're not familiar with PEAR and its installation, see Chapter 12, "Using PEAR," or http://pear.php.net.
Simple Authentication
This first, simple authentication example shows how easily you can implement authentication in a page. I'll run through the syntax and concepts first, and then create a script that executes it all.
To begin, require the Auth class:
require_once ('Auth.php');
Next, you'll need to define a function that creates a login form. This function will be called when an unauthorized user is trying to access a page. The form should use the POST method and have inputs called username and password.
Then, for database-driven authentication, which is the norm, you'll need to create a "DSN" within an options array. DSN stands for data source name. It's just a string of information that indicates the type of database application being used, the username, password, and hostname to connect as, and the database to select. That code might be:
$options = array('dsn' => 'mysql://username:password@localhost/databasename');
Now that those two things have been defined—the function that makes the login form and the DSN—you can create an object of Auth type. Provide this object three arguments: the type of authentication back end to use (e.g., database or file), the options (that correspond to the authentication type), and the name of the login function:
$auth = new Auth('DB', $options, 'login_form_function_name');
The DB option tells Auth to use the PEAR DB package. If you wanted to use a file system instead, you would use File as the first argument and the name of the file as the second.
Now, start the authentication process:
$auth->start();
From there, you can check if a user is authenticated by calling the checkAuth() method:
if ($auth->checkAuth()) { // Do whatever.
And that's simple authentication in a nutshell! This next example will implement all this. It will also invoke the addUser() method to add a new authenticated user, which can then be used for logging in. One last note: this example will make use of a database called auth, which must be created prior to writing this script. It should have a table called auth, defined like so:
CREATE TABLE auth ( username VARCHAR(50) NOT NULL, password VARCHAR(32) NOT NULL, PRIMARY KEY (username), KEY (password) )
Be certain that you've created this database and table (Figure 4.8), and that you have created a MySQL user that has access to them, prior to going any further.
Figure 4.8 Creating the database and table required by the simple authentication example.
To perform simple authentication
- Begin a new PHP script in your text editor or IDE (Script 4.3).
<?php # Script 4.3 - login.php
Because Auth relies on sessions (it'll start the sessions for you), it's best to do as much as you can before sending any HTML to the Web browser. So I'll write most of the authentication code, and only then begin the HTML page.Script 4.3. Using PEAR Auth and a MySQLtable, this script enforces authentication.
1 <?php # Script 4.3 - login.php 2 3 /* This page uses PEAR Auth to control access. 4 * This assumes a database called "auth", 5 * accessible to a MySQL user of "username@localhost" 6 * with a password of "password". 7 * Table definition: 8 9 CREATE TABLE auth ( 10 username VARCHAR(50) default '' NOT NULL, 11 password VARCHAR(32) default '' NOT NULL, 12 PRIMARY KEY (username), 13 KEY (password) 14 ) 15 * MD5() is used to encrypt the passwords. 16 */ 17 18 // Need the PEAR class: 19 require_once ('Auth.php'); 20 21 // Function for showing a login form: 22 function show_login_form() { 23 24 echo '<form method="post" action="login.php"> 25 <p>Username <input type="text" name="username" /></p> 26 <p>Password <input type="password" name="password" /></p> 27 <input type="submit" value="Login" /> 28 </form><br /> 29 '; 30 31 } // End of show_login_form() function. 32 33 // Connect to the database: 34 $options = array('dsn' => 'mysql://username:password@localhost/auth'); 35 36 // Create the Auth object: 37 $auth = new Auth('DB', $options, 'show_login_form'); 38 39 // Add a new user: 40 $auth->addUser('me', 'mypass'); 41 42 ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 43 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 44 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 45 <head> 46 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> 47 <title>Restricted Page</title> 48 </head> 49 <body> 50 <?php 51 52 // Start the authorization: 53 $auth->start(); 54 55 // Confirm authorization: 56 if ($auth->checkAuth()) { 57 58 echo '<p>You are logged in and can read this. How cool is that?</p>'; 59 60 } else { // Unauthorized. 61 62 echo '<p>You must be logged in to access this page.</p>'; 63 64 } 65 66 ?> 67 </body> 68 </html>
- Include the Auth class.
require_once ('Auth.php');
If you haven't installed PEAR Auth yet, do so now. See the PEAR manual for instructions. - Define the function that creates the login form.
function show_login_form() { echo '<form method="post" action="login.php"> <p>Username <input type="text" name="username" /></p> <p>Password <input type="password" name="password" /></p> <input type="submit" value="Login" /> </form><br /> '; }
The only requirements are that this form has one input called username and another called password. - Create the options array.
$options = array('dsn' => 'mysql://username:password@localhost/auth');
This code says that a connection should be made to a MySQL database called auth, using username as the username, password as the password, and localhost as the host. - Create the Auth object.
$auth = new Auth('DB', $options, 'show_login_form');
Add a new user and complete the PHP section.
$auth->addUser('me', 'mypass'); ?>
The addUser() functions takes the username as its first argument and the password as the second. This record will be added to the database as soon as the script is first run (Figure 4.9). Because the username column in the table is defined as a primary key, MySQL will never allow a second user with the name of me to be added.
Figure 4.9 One user has been added to the table. The password is encrypted using the MD5() function.
In a real application, you'd have a registration process that would just end up calling this function in the end.
- Add the initial HTML code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Restricted Page</title> </head> <body>
- Start the authentication.
<?php $auth->start();
- Display different messages based upon the authentication status.
if ($auth->checkAuth()) { echo '<p>You are logged in and can read this. How cool is that?</p>'; } else { echo '<p>You must be logged in to access this page.</p>'; }
When a user first comes to this page, and $auth->checkAuth() is false, they'll see the login form plus this second message (Figure 4.10). After logging in with a valid username/password combination, they'll see this first message (Figure 4.11)Figure 4.10 When first arriving at this page, or after an unsuccessful login attempt, a user sees this.
Figure 4.11 The result after successfully logging in.
- Complete the page.
?> </body> </html>
Save the file as login.php, place it in your Web directory, and test in your Web browser.
Use me as the username and mypass as the password.
Custom Authentication
The preceding example does a fine job of showing how easy it is to use PEAR Auth, but it doesn't demonstrate how you would actually use it in a more full-fledged application. By this I mean a site that has a table with more than two columns and needs to store, and retrieve, other information as well.
The first change you'll need to make is to the options array used when creating the Auth object. Different storage types ("containers" in Auth parlance) have different options. Table 4.3 lists some of the other options you can use with DB.
Table 4.3. These are some of the parameters you can set when creating a new Auth object that uses DB.
DB Container Options |
|
Option |
Indicates |
dsn |
The Data Source Name |
table |
The database table to use |
usernamecol |
The name of the username column |
passwordcol |
The name of the password column |
db_fields |
What other table fields should be selected |
cryptType |
The function used to encrypt the password |
For example, the DB container will use a combination of the usernamecol and passwordcol (encrypted using cryptType) to authenticate the user against the submitted values. The preceding example used the defaults, but you can change this information easily. Just as important, you can specify what other database columns should be retrieved. These will then be available in the session data and can be retrieved in your script through the getAuthData() function:
echo $auth->getAuthData('column_name');
Three other functions you can use to customize the authentication are setExpire(), setIdle(), and setSessionName(). The first takes a value, in seconds, when the session should be set to expire. The second takes a value, in seconds, when a user should be considered idle (because it's been too long since their last activity). The third function changes the name of the session (which is PHPSESSID, by default).
For this next example, a new table will be used, still in the auth database. To create it, use this SQL command (Figure 4.12):
CREATE TABLE users ( user_id INT UNSIGNED NOT NULL AUTO_INCREMENT, email VARCHAR(60) NOT NULL, pass CHAR(40) NOT NULL, first_name VARCHAR (20) NOT NULL, last_name VARCHAR(40) NOT NULL, PRIMARY KEY (user_id), UNIQUE (email), KEY (email, pass) )
Figure 4.12 Creating the table used by the custom authentication system.
This table represents how you might already have some sort of user table, with its own columns, that you'd want to use with Auth.
To use custom authentication
- Begin a new PHP script in your text editor or IDE, starting with the HTML (Script 4.4).
<?php # Script 4.4 - custom_auth.php require_once ('Auth.php');
Script 4.4. In this script, Auth uses a different table, different column names, and a different encryption function for the password. It selects every column from the table, making all the previously stored data available to the page.
1 <?php # Script 4.4 - custom_auth.php 2 3 /* This page uses PEAR Auth to control access. 4 * This assumes a database called "auth", 5 * accessible to a MySQL user of "username@localhost" 6 * with a password of "password". 7 * Table definition: 8 9 CREATE TABLE users ( 10 user_id INT UNSIGNED NOT NULL AUTO_INCREMENT, 11 email VARCHAR(60) NOT NULL, 12 pass CHAR(40) NOT NULL, 13 first_name VARCHAR (20) NOT NULL, 14 last_name VARCHAR(40) NOT NULL, 15 PRIMARY KEY (user_id), 16 UNIQUE (email), 17 KEY (email, pass) 18 ) 19 20 * SHA1() is used to encrypt the passwords. 21 */ 22 23 // Need the PEAR class: 24 require_once ('Auth.php'); 25 26 // Function for showing a login form: 27 function show_login_form() { 28 29 echo '<form method="post" action="custom_auth.php"> 30 <p>Email <input type="text" name="username" /></p> 31 <p>Password <input type="password" name="password" /></p> 32 <input type="submit" value="Login" /> 33 </form><br /> 34 '; 35 36 } // End of show_login_form() function. 37 38 // All options: 39 // Use specific username and password columns. 40 // Use SHA1() to encrypt the passwords. 41 // Retrieve all fields. 42 $options = array( 43 'dsn' => 'mysql://username:password@localhost/auth', 44 'table' => 'users', 45 'usernamecol' => 'email', 46 'passwordcol' => 'pass', 47 'cryptType' => 'sha1', 48 'db_fields' => '*' 49 ); 50 51 // Create the Auth object: 52 $auth = new Auth('DB', $options, 'show_login_form'); 53 54 // Add a new user: 55 $auth->addUser('me@example.com', 'mypass', array('first_name' => 'Larry', 'last_name' => 'Ullman')); 56 57 ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 58 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 59 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 60 <head> 61 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> 62 <title>Restricted Page</title> 63 </head> 64 <body> 65 <?php 66 67 // Start the authorization: 68 $auth->start(); 69 70 // Confirm authorization: 71 if ($auth->checkAuth()) { 72 73 // Print the user's name: 74 echo "<p>You, {$auth->getAuthData('first_name')} {$auth->getAuthData('last_name')}, are logged in and can read this. How cool is that?</p>"; 75 76 } else { // Unauthorized. 77 78 echo '<p>You must be logged in to access this page.</p>'; 79 80 } 81 82 ?> 83 </body> 84 </html>
- Define the show_login_form() function.
function show_login_form() { echo '<form method="post" action="custom_auth.php"> <p>Email <input type="text" name="username" /></p> <p>Password <input type="password" name="password" /></p> <input type="submit" value="Login" /> </form><br /> '; }
The function is mostly the same as it was before, except this time the action points to this script, custom_auth.php. The form also labels the one input as Email (Figure 4.13), even though it's named username (as required).Figure 4.13 The customized login form.
- Establish the authorization options and create the object.
$options = array( 'dsn' => 'mysql://username:password@localhost/auth', 'table' => 'users', 'usernamecol' => 'email', 'passwordcol' => 'pass', 'cryptType' => 'sha1', 'db_fields' => '*' ); $auth = new Auth('DB', $options, 'show_login_form');
The DSN is the same as it was before. Next, the table, usernamecol, and passwordcol values are all specified. These match the table already created (Figure 4.12). The cryptType value says that the passwords should be encoded using SHA1(), instead of the default MD5(). The final element in the $options array says that every column from the table should be retrieved. In this particular script, this will allow the page to refer to the logged-in user by name. - Add a new user and complete the initial PHP section (Figure 4.14).
$auth->addUser('me@example.com', 'mypass', array('first_name' => 'Larry', 'last_name' => 'Ullman')); ?>
Figure 4.14 A sample user has been added to the users table.
INSERT INTO users (email, pass, first_name, last_name) VALUES ('me@example.com', SHA1('mypass'), 'Larry', 'Ullman')
- Create the initial HTML code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 'last_ <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Restricted Page</title> </head> <body>
- Start the authorization.
<?php $auth->start();
- Print the authorization status.
if ($auth->checkAuth()) { echo "<p>You, {$auth->get AuthData('first_name')} {$auth->getAuthData('last_name')}, are logged in and can read this. How cool is that?</p>"; } else { echo '<p>You must be logged in to access this page.</p>'; }
The result if the user isn't logged in looks like Figure 4.13. When the user does log in, they are greeted by name (Figure 4.15). The getAuthData() function can access the values selected from the table and stored in the authentication session.Figure 4.15 After successfully logging in, the user is greeted by name. The name was pulled from the table and stored in the session.
- Complete the page.
?> </body> </html>
- Save the file as custom_auth.php, place it in your Web directory, and test in your Web browser.