Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

Security Techniques

This chapter is from the book

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

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:


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:

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

Figure 4.8 Creating the database and table required by the simple authentication example.

To perform simple authentication

  1. 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
    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:
    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    */
    18   // Need the PEAR class:
    19   require_once ('Auth.php');
    21   // Function for showing a login form:
    22   function show_login_form() {
    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   ';
    31   } // End of show_login_form() function.
    33   // Connect to the database:
    34   $options = array('dsn' => 'mysql://username:password@localhost/auth');
    36   // Create the Auth object:
    37   $auth = new Auth('DB', $options, 'show_login_form');
    39   // Add a new user:
    40   $auth->addUser('me', 'mypass');
    42   ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    43          "">
    44   <html xmlns="" 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
    52   // Start the authorization:
    53   $auth->start();
    55   // Confirm authorization:
    56   if ($auth->checkAuth()) {
    58       echo '<p>You are logged in and can read this. How cool is that?</p>';
    60   } else { // Unauthorized.
    62       echo '<p>You must be logged in to access this page.</p>';
    64   }
    66   ?>
    67   </body>
    68   </html>
  2. 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.
  3. 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.
  4. 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.
  5. Create the Auth object.
    $auth = new Auth('DB', $options, 'show_login_form');
  6. 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

    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.

  7. Add the initial HTML code.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    <html xmlns="" xml:lang="en" lang="en">
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
        <title>Restricted Page</title>
  8. Start the authentication.
  9. 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

    Figure 4.10 When first arriving at this page, or after an unsuccessful login attempt, a user sees this.

    Figure 4.11

    Figure 4.11 The result after successfully logging in.

  10. Complete the page.
  11. 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




The Data Source Name


The database table to use


The name of the username column


The name of the password column


What other table fields should be selected


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):

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

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

  1. 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
    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:
    9        CREATE TABLE users (
    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       )
    20    *  SHA1() is used to encrypt the passwords.
    21    */
    23   // Need the PEAR class:
    24   require_once ('Auth.php');
    26   // Function for showing a login form:
    27   function show_login_form() {
    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   ';
    36   } // End of show_login_form() function.
    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   );
    51   // Create the Auth object:
    52   $auth = new Auth('DB', $options, 'show_login_form');
    54   // Add a new user:
    55   $auth->addUser('', 'mypass', array('first_name' => 'Larry', 'last_name' =>
    57   ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    58       "">
    59   <html xmlns="" 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
    67   // Start the authorization:
    68   $auth->start();
    70   // Confirm authorization:
    71   if ($auth->checkAuth()) {
    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>";
    76   } else { // Unauthorized.
    78       echo '<p>You must be logged in to access this page.</p>';
    80   }
    82   ?>
    83   </body>
    84   </html>
  2. 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

    Figure 4.13 The customized login form.

  3. 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.
  4. Add a new user and complete the initial PHP section (Figure 4.14).
    $auth->addUser('', 'mypass', array('first_name' => 'Larry', 'last_name' => 'Ullman'));
    Figure 4.14

    Figure 4.14 A sample user has been added to the users table.

    Because the table has more than just the two columns, the extra columns and values have to be provided, as an array, as the third argument to the addUser() method. This call of the function is the equivalent of running this query:
    INSERT INTO users (email, pass, first_name, last_name) VALUES ('', SHA1('mypass'), 'Larry', 'Ullman')
  5. Create the initial HTML code.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    ""> 'last_
    <html xmlns="" xml:lang="en" lang="en">
         <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
         <title>Restricted Page</title>
  6. Start the authorization.
  7. 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

    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.

  8. Complete the page.
  9. Save the file as custom_auth.php, place it in your Web directory, and test in your Web browser.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020