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

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

From the book Authenticating User Credentials with Zend_Auth

Authenticating User Credentials with Zend_Auth

The end result of the improved registration form that you just created is the same as Dreamweaver’s built-in Insert Record server behavior—it inserts user details in the database. Dreamweaver’s User Authentication server behaviors can still be used to control access to pages. However, ZF makes it easy to create scripts to authenticate user credentials. Using external files for the scripts that control access and log out users simplifies their inclusion in any page.

Controlling user access with Zend_Auth

The Zend_Auth class creates a singleton object, which means that only one instance can exist at a time. In practical terms, the only difference is that you use getInstance() instead of the new keyword like this:

$auth = Zend_Auth::getInstance();

Zend_Auth is capable of using a variety of authentication methods. When the user credentials are stored in a database, authentication is done by an adapter called Zend_Auth_Adapter_DbTable, which takes the following five arguments:

  • A Zend_Db object that connects to the database
  • The name of the table that contains the user credentials
  • The name of the column that contains the username
  • The name of the password column
  • The encryption, if any, to be applied to the password

The fifth argument uses a question mark as a placeholder for the password. The users table uses sha1() encryption, so you create an adapter like this:

$adapter = new Zend_Auth_Adapter_DbTable($dbRead, ‘users’, ‘username’,
‘password’, ‘sha1(?)’);

When a user logs in, pass the username and password to the adapter like this:

$adapter->setIdentity($_POST[‘username’]);
$adapter->setCredential($_POST[‘password’]);

To check whether the user’s credentials are valid, pass the adapter to the Zend_Auth object’s authenticate() method:

$result = $auth->authenticate($adapter);

Finally, if the login succeeds, store the user’s details like this:

if ($result->isValid()) {
  $storage = $auth->getStorage();
  $storage->write($adapter->getResultRowObject(
    array(‘username’, ‘first_name’, ‘family_name’)));
}

The array passed as an argument to the getResultRowObject() method is a list of the database fields you want to store. Dreamweaver’s built-in Log In User server behavior stores only the username and access level, if any. Zend_Auth gives you access to as much information about the user as you want—provided, of course, it’s stored in the database.

You restrict access to pages by using the hasIdentity() method, which returns TRUE if the user has logged in.

To access details of a logged-in user, use the getIdentity() method like this:

$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
  $identity = $auth->getIdentity();
}

The details can then be accessed as properties of $identity, for example:

$identity->first_name

To log out a visitor, use the clearIdentity() method.

Creating the login script

The Log In User server behavior that you used in Lesson 6 sends the user to another page on failure or displays the login form again without explanation. This time you’ll display an error message so the user knows what’s happened.

  1. Create a new PHP page, and save it as user_authentication.php in lesson07/workfiles/scripts. The page will contain only PHP code, so delete the HTML inserted by Dreamweaver, and add an opening PHP tag.
  2. To control the error message, create a FALSE Boolean variable:
  3. $failed = FALSE;
    

    If the login fails, this will be reset to TRUE and display the message.

  4. The login script should run only if the form is submitted. Add a conditional statement to include library.php if the $_POST array equates to TRUE:
  5. if ($_POST) {
      require_once(‘library.php’);
      // check the user’s credentials
    }
    
  6. The script uses objects, so add try and catch blocks inside the conditional statement, and get an instance of Zend_Auth in the try block.
  7. try {
      $auth = Zend_Auth::getInstance();
    } catch (Exception $e) {
      echo $e->getMessage();
    }
    

    The rest of the script goes inside the try block.

  8. Create a Zend_Auth_Adapter_DbTable object. A quick way to select its code hint is by typing hada after the new keyword. This takes five arguments, but Dreamweaver helps you by highlighting the current argument in bold.
  9. The code for this line should look like this:

    $adapter = new Zend_Auth_Adapter_DbTable($dbRead, ‘users’, ‘username’,
    ‘password’, ‘sha1(?)’);
    
  10. Set the identity and credential values for the adapter. They come from the username and password values in the $_POST array:
  11. $adapter->setIdentity($_POST[‘username’]);
    $adapter->setCredential($_POST[‘password’]);
    
  12. Pass the adapter to the authenticate() method of the Zend_Auth object, and save the result in a variable:
  13. $result = $auth->authenticate($adapter);
    
  14. Use the isValid() method to determine whether the user’s credentials are correct. If they are, store the details, and use header() to redirect the user to members_only.php. If the login attempt fails, reset $failed to TRUE. The code looks like this:
  15. if ($result->isValid()) {
      $storage = $auth->getStorage();
      $storage->write($adapter->getResultRowObject(array(
        ‘username’, ‘first_name’, ‘family_name’)));
      header(‘Location: members_only.php’);
      exit;
    } else {
      $failed = TRUE;
    }
    

Testing the login script

To use the login script, include it above the DOCTYPE declaration of the login page, and add a conditional statement to show an error message if the login fails.

  1. Copy login.php and members_only.php from lesson07/start to lesson07/workfiles.
  2. Include user_authentication.php in login.php by adding the following above the DOCTYPE declaration:
  3. <?php
    require_once(‘scripts/user_authentication.php’);
    ?>
    
  4. In Design view, insert a new paragraph after the Members Only heading, and type Login failed. Check username and password.
  5. With the insertion point anywhere in the paragraph, choose warning from the Class menu in the Property inspector. This turns the text bold red.

  6. Switch to Code view, and wrap the paragraph you just created in a conditional statement like this:
  7. <?php if ($failed) { ?>
    <p class="warning">Login failed. Please check username and password.</p>
    <?php } ?>
    

    The script in user_authentication.php sets $failed to FALSE and changes it to TRUE only if a login attempt fails, so this prevents the error message from being shown unless the user’s credentials are rejected.

  8. Save login.php, and test it in Live View or a browser. When the page first loads, the error message is not displayed. Try to log in using an invalid username or password. The error message is displayed.
  9. Click “Sign in” without typing anything in either field. You get the following message: “A value for the identity was not provided prior to authentication with Zend_Auth_Adapter_DbTable.”
  10. This comes from the catch block. Failing to enter anything in the Username field has caused Zend_Auth to throw an exception. This is more elegant than the lengthy error message you get without try and catch, but it’s not something you want to show visitors to your site.

  11. Switch back to user_authentication.php, and add another conditional statement inside the existing one near the top of the script:
  12. if ($_POST) {
      if (empty($_POST['username']) || empty($_POST['password'])) {
        $failed = TRUE;
      } else {
        require_once('library.php');
    

    This uses empty() to test if $_POST[‘username’] or $_POST[‘password’] contains a value. If either is empty, $failed is reset to TRUE. The authentication script is now inside an else block that is executed only if $_POST[‘username’] and $_POST[‘password’] both have values.

  13. A red marker on the last line of the script reminds you that you need to add a closing curly brace to match the opening one of the else block. Technically speaking, the missing brace goes between the last two braces at the bottom of the script, but you can put it on the final line, and the red marker goes away.
  14. Save user_authentication.php, and test the login form again without filling in the fields. This time you get your custom error message in red.
  15. Test the login form with a registered username and password. When you click “Sign in,” you are taken to members_only.php.
  16. You can compare your code with lesson07/completed/login.php and lesson07/completed/scripts/user_authentication01.php.

Password-protecting pages

Building the login script was the complex part. To restrict access to a page, you use the hasIdentity() method, which returns TRUE or FALSE. If the user is logged in, you retrieve his or her details with getIdentity(). Otherwise, you redirect the user to the login page.

  1. Create a PHP page, and save it as restrict_access.php in lesson07/workfiles/scripts. Delete the HTML inserted by Dreamweaver.
  2. The script is so short; here it is in its entirety:
  3. <?php
    require_once(‘library.php’);
    try {
      $auth = Zend_Auth::getInstance();
      if ($auth->hasIdentity()) {
        $identity = $auth->getIdentity();
      } else {
        header(‘Location: login.php’);
        exit;
      }
    } catch (Exception $e) {
      echo $e->getMessage();
    }
    

    This includes library.php and creates an instance of Zend_Auth. The conditional statement checks whether the user is logged in. If it succeeds, the user’s details are stored in $identity. Otherwise, the page is redirected to login.php, and exit ensures that the script comes to an immediate halt, preventing the protected page from being displayed.

  4. To password-protect members_only.php, just include this script above the DOCTYPE declaration like this:
  5. <?php
    require_once(‘scripts/restrict_access.php’);
    ?>
    

    Assuming you’re already logged in, you need to log out before you can test this. For that, you need a logout button and script, which is coming up next.

Creating a logout system

Zend_Auth makes logging out easy with the clearIdentity() method. You can add the necessary code to user_authentication.php, and use a link to login.php to log out the user. A query string at the end of the link triggers the logout.

  1. Create a new paragraph in members_only.php, and type Log Out.
  2. Select the text, and link to login.php. Add ?logout to the end of the link. You can do this in the Link field of the Property inspector or in Code view. Save members_only.php.
  3. Switch to user_authentication.php, and add the following code at the bottom of the page:
  4. if (isset($_GET[‘logout’])) {
      require_once(‘library.php’);
      try {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
      } catch (Exception $e) {
          echo $e->getMessage();
      }
    }
    

    Values passed through a query string are in the $_GET array. This uses isset() to see if $_GET[‘logout’] exists. If it does, the ZF files are included, an instance of Zend_Auth is created, and the clearIdentity() method performs the logout. That’s all there is to it. The session variables storing the user’s details are deleted automatically.

  5. Save user_authentication.php, and load members_only.php in a browser or Live View. If the page displays, click the “Log out” link. You will be taken to the login form.
  6. Log in, and click the “Log out” link again.
  7. Now try to access members_only.php directly. You will be denied access and taken to the login form.

Displaying a logged-in user’s details

The code in restrict_access.php calls the getIdentity() method and stores the user’s username, first name, and family name as properties of $identity. This makes it possible to greet a user by name after logging in.

  1. In Code view, amend the beginning of the first paragraph in members_only.php like this:
  2. <p>Hi, <?php echo "$identity->first_name $identity->family_name"; ?>.
    ÂYou're in!
    

    The column names are treated as properties of $identity, allowing you to access the information they contain about the user with the -> operator.

  3. Save members_only.php, and log back in to be greeted by name.

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.

Overview


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.

Surveys

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.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

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.

Security


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

Children


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

Marketing


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 customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


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: www.peachpit.com/u.aspx.

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 NevadaDesignatedRequest@pearson.com.

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.

Links


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