Using the PEAR library HTML_QuickForm2 to create a simple authentication form with a custom validation callback

In this code snippet tutorial, I'll show how you can use the PEAR library HTML_QuickForm2 to create a simple authentication form with a custom validation callback.

<?php

// start session
session_start();

// check if user needs to authenticate
if (empty($_SESSION['accountID'])) {

  // show form
  require_once('HTML/QuickForm2.php');
  // NOTE: have the form submit to itself
  $form = new HTML_QuickForm2('login', 'post', array('action' => $_SERVER['REQUEST_URI']));

  // add username field
  $username = $form->addElement('text', 'username')->setLabel('username:');
  $username->addRule('required', 'username is required.');

  // add password field
  $password = $form->addElement('password', 'password')->setLabel('password:');
  $password->addRule('required', 'password is required.');

  // add submit button
  $form->addElement('submit', null, array('value' => 'submit'));

  // add filter to trim all elements
  $form->addRecursiveFilter('trim');

  // add custom validation rule
  $form->addRule(
    'callback',
    'authentication failed.',
    array(
      'callback' => 'portal_authentication_validation',
    )
  );

  // check if form validates
  if ($form->validate()) {

    // at this point, the form has validated, set session data as authentication
    // NOTE: at this point, the account ID should be fetched from the database, etc
    $_SESSION['accountID'] = 'some_val';

    // redirect user (reload url)
    header("Location: " . $_SERVER['REQUEST_URI']);
    die;

  }
  // form did not pass validation, display form
  else {

    // display form
    echo $form;

  }

}
// user is already authenticated..
else {

  // do something here!
  echo "Hello Auth User!";

}

// defines custom validation callback function
function portal_authentication_validation($form_args) {

  /*
  Args..
  $form_args['username']
  $form_args['password']
  */

  // At this point, query the database to validate username/password, etc
  if ($user_and_password_validates) {
    return TRUE:
  }

  return FALSE;

}
?>

The above code will result in the following form:

Authentication form