PEAR is archived and read-only

This mirror preserves historical PEAR package releases and metadata so existing references remain available.

Home » Authentication » Auth » Manual

Provides a framework for user authentication.

Introduction

Introduction – A usage example

Auth tutorial

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:

Typical usage example for PEAR::Auth

<?php
require_once "Auth.php";

// Takes three arguments: last attempted username, the authorization
// status, and the Auth object. 
// We won't use them in this simple demonstration -- but you can use them
// to do neat things.
function loginFunction($username = null, $status = null, &$auth = null)
{
    /*
     * Change the HTML output so that it fits to your
     * application.
     */
    echo "<form method=\"post\" action=\"test.php\">";
    echo "<input type=\"text\" name=\"username\">";
    echo "<input type=\"password\" name=\"password\">";
    echo "<input type=\"submit\">";
    echo "</form>";
}

$options = array(
  'dsn' => "mysql://user:password@localhost/database",
  );
$a = new Auth("DB", $options, "loginFunction");

$a->start();

if ($a->checkAuth()) {
    /*
     * The output of your site goes here.
     */
}
?>

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.

Using optional authentication

<?php
// In this test, the file is named "test.php".

require_once "Auth.php";

function loginFunction()
{
     /*
      * Change the HTML output so that it fits to your
      * application.
      */
     echo "<form method=\"post\" action=\"test.php?login=1\">";
     echo "<input type=\"text\" name=\"username\">";
     echo "<input type=\"password\" name=\"password\">";
     echo "<input type=\"submit\">";
     echo "</form>";
}

if (isset($_GET['login']) && $_GET['login'] == 1) {
     $optional = true;
} else {
     $optional = false;
}

$options = array(
  'dsn' => "mysql://user:password@localhost/database",
  );
$a = new Auth("DB", $options, "loginFunction", $optional);

$a->start();

echo "Everybody can see this text!<br />";

if (!isset($_GET['login'])) {
     echo "<a href=\"test.php?login=1\">Click here to log in</a>\n";
}

if ($a->getAuth()) {
     echo "One can only see this if he is logged in!";
}
?>

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!".

Logout functionality

The following example performs a "logout" for the current user and displays the login form again.

<?php
$myauth->start();
if ($_GET['action'] == "logout" && $myauth->checkAuth()) {
    $myauth->logout();
    $myauth->start();
}
?>

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.

Auth Options

Auth Options – Options for controlling the behaviour of Auth

Auth Options

In addition to the options available for each container a series of options can be included that control the behaviour of Auth itself.

Available Options
Option Data Type Default value Description
"sessionName" string "_authsession" The name used to identify this Auth session. See Auth::setSessionName()
"allowLogin" boolean TRUE Whether to allow logins to be performed on this page. See Auth::setAllowLogin()
"postUsername" string "username" The name of the form field that contains the username to authenticate.
"postPassword" string "password" The name of the form field that contains the password to authenticate.
"advancedsecurity" boolean FALSE Whether to enable the advanced security features. See Auth::setAdvancedSecurity()
"enableLogging" boolean FALSE Whether to enable the internal logging system. See the Logging Examples and Auth::attachLogObserver()
"regenerateSessionId" boolean FALSE Set to TRUE to regenerate the session id on every page load or leave as FALSE to regenerate only upon new login.

Logging

Logging – Introduction

Overview

Since version 1.5.0 PEAR::Auth provides a facility for retrieving logs of its internal behaviour. This is implemented using PEAR::Log and its log observer components.

Auth provides two levels of log messages which map to the Log priority levels PEAR_LOG_INFO and PEAR_LOG_DEBUG.

PEAR_LOG_INFO messages provide basic information about Auth's decisions, for example user authentication successful/failed, rendering login screen.

PEAR_LOG_DEBUG messages provide detailed information about what is happening within the internals of Auth, for example which functions are called, logic tracking for the Authentication method, what SQL queries are being run against the database backends.

Example

Typical usage example for accessing the logs from PEAR::Auth

<?php
require_once "Auth.php";
require_once 'Log.php';
require_once 'Log/observer.php';

// Callback function to display login form
function loginFunction($username = null, $status = null, &$auth = null)
{
    /*
     * Change the HTML output so that it fits to your
     * application.
     */
    echo "<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">";
    echo "Username: <input type=\"text\" name=\"username\"><br/>";
    echo "Password: <input type=\"password\" name=\"password\"><br/>";
    echo "<input type=\"submit\">";
    echo "</form>";
}

class Auth_Log_Observer extends Log_observer {

    var $messages = array();

    function notify($event) {

        $this->messages[] = $event;

    }

}

$options = array(
        'enableLogging' => true,
        'cryptType' => 'md5',
        'users' => array(
            'guest' => md5('password'),
            ),
        );
$a = new Auth("Array", $options, "loginFunction");

$infoObserver = new Auth_Log_Observer(PEAR_LOG_INFO);

$a->attachLogObserver($infoObserver);

$debugObserver = new Auth_Log_Observer(PEAR_LOG_DEBUG);

$a->attachLogObserver($debugObserver);

$a->start();

if ($a->checkAuth()) {
    /*
     * The output of your site goes here.
     */
    print "Authentication Successful.<br/>";
}

print '<h3>Logging Output:</h3>'
    .'<b>PEAR_LOG_INFO level messages:</b><br/>';

foreach ($infoObserver->messages as $event) {
    print $event['priority'].': '.$event['message'].'<br/>';
}

print '<br/>'
    .'<b>PEAR_LOG_DEBUG level messages:</b><br/>';

foreach ($debugObserver->messages as $event) {
    print $event['priority'].': '.$event['message'].'<br/>';
}

print '<br/>';
?>

To enable logging pass the option "enableLogging" with the value TRUE in the options array in the second parameter to the Auth constructor.

To retrieve the log messages from Auth create a new subclass of Log_Observer that implements a notify() function to perform whatever actions you want on the log messages.

Once defined pass an instance of your new Log_Observer instance to Auth::attachLogObserver().

To limit the types of messages you receive in the Log_Observer pass either PEAR_LOG_INFO or PEAR_LOG_DEBUG as the first parameter to the Log_Observer. The default is PEAR_LOG_INFO. For more information on this filtering see the Log Documentation.

<?php
$observer = new My_Log_Observer(PEAR_LOG_DEBUG);
?>

Note

This container has only been available since version 1.5.0.

Storage drivers

Storage drivers – Introduction

Overview

PEAR::Auth uses a number of so called storage containers to store the login data. The following passages describe all of them. If the containers that come with the package don't fit your needs, it is easy to create custom ones, also.

Available Containers

Array

Storage container using a PHP Array.

DB

Storage container using PEAR DB.

DBLite

A simplified version of the DB container that only provides user authentication. No user management functions are provided.

File

Storage container using PEAR File_Passwd.

IMAP

Storage container for use against IMAP servers.

KADM5

Storage container for use against Kerberos V servers.

LDAP

Storage container for use against LDAP servers.

MDB

Storage container using PEAR MDB.

MDB2

Storage container using PEAR MDB2.

Multiple

Storage container for using multiple Auth_Containers in a fall through manner.

PEAR

Storage container for use against the PEAR website.

POP3

Storage container for use against a POP3 server.

RADIUS

Storage container for use against a RADIUS server.

SAP

Storage container for use against a SAP server.

SMBPasswd

Storage container using PEAR File_SMBPasswd.

SOAP

Storage container for use against a SOAP service using PEAR SOAP as the client.

SOAP5

Storage container for use against a SOAP service using PHP5 SOAP as the client.

vpopmail

Storage container using vpopmail.

Custom

Instructions on creating a custom storage container.

Auth_Container_Array

Auth_Container_Array – Authenticate against an array of usernames and passwords

Array

This storage container provides a simple way to store a limited number of username/password pairs within the source code of the script.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"cryptType" string "none" The encryption type the password is stored in.
"users" array array() Named array of usernames and password hashes.
<?php
array(
    'guest' => '084e0343a0486ff05530df6c705c8bb4', // password guest
    'georg' => 'fc77dba827fcc88e0243404572c51325' // password georg
)
?>

Auth_Container_DB

Auth_Container_DB – Authenticate against a database using DB

DB Container

This container makes use of PEAR::DB abstraction layer for database access. That means that you can use all databases that are supported by the DB abstraction layer to store the login data.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"dsn" string " A valid and well-formed DSN .
"table" string "auth" The name of the database table, where the authorization data is stored.
"usernamecol" string "username" The name of the column, where the username is stored
"passwordcol" string "password" The name of the column, where the crypted password is stored.
"db_fields" array array() An array of extra fields to retrieve when loading the user details.
"cryptType" string "md5" The encryption type the password is stored in.
"auto_quote" boolean TRUE Whether to enable automatic quoting of database table and field names.
"db_options" array array() An array of options to be passed to the PEAR::DB constructor. See PEAR::DB::setOption() for more information.
"db_where" string " A string to be appended to the WHERE clause of queries against the database. It is appended to the queries used in fetchData(), listUsers(), removeUser() and changePassword(). Available since Auth 1.5.0.

Auth_Container_DBLite

Auth_Container_DBLite – Authenticate against a database using DB

DBLite Container

The DBLite container is a simplified version of the DB container. It does away with all the code related to user management and simply provides user authentication.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"dsn" string " A valid and well-formed DSN .
"table" string "auth" The name of the database table, where the authorization data is stored.
"usernamecol" string "username" The name of the column, where the username is stored
"passwordcol" string "password" The name of the column, where the crypted password is stored.
"db_fields" array array() An array of extra fields to retrieve when loading the user details.
"cryptType" string "md5" The encryption type the password is stored in.
"auto_quote" boolean TRUE Whether to enable automatic quoting of database table and field names.
"db_options" array array() An array of options to be passed to the PEAR::DB constructor. See PEAR::DB::setOption() for more information.
"db_where" string " A string to be appended to the WHERE clause of queries against the database. It is appended to the queries used in fetchData(). Available since Auth 1.5.0.

Auth_Container_File

Auth_Container_File – Authenticate a password file using File_Passwd

File Container

description

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"type" string "Cvs" The format of the file we are authenticating against. For a list of available types see the PEAR::File_Passwd documentation.
"file" string " The filename of the file to use.

Auth_Container_IMAP

Auth_Container_IMAP – Authenticate against an IMAP server

IMAP Container

This storage container connects to the specified IMAP server and tries to login there with the specified username/password.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"host" string "localhost" The hostname or the IP address of the IMAP server
"port" integer 143 The port where the IMAP server is listening
"baseDSN" string "

This controls the methods used to connect. Like SSL, TLS and certificate validation.

To connect to an SSL IMAP server: "/imap/ssl"

To connect to an SSL IMAP server with a self-signed certificate: "'/imap/ssl/novalidate-cert'"

Further options may be available and can be found on the php site at http://www.php.net/manual/function.imap-open.php.

"timeout" integer 20 Timeout in seconds for connecting to the server.
"checkServer" boolean TRUE Whether to check if we can connect to the server when starting container.

Auth_Container_KADM5

Auth_Container_KADM5 – Authenticate against a Kerberos 5 server

KADM5 Container

This storage driver makes use of the PECL kadm5 extension to provide authentication services against a Kerberos V.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"hostname" string "localhost" The hostname or IP address of the Kerberos V server.
"realm" string " The Kerberos V realm to authenticate in.
"timeout" integer 10 Timeout in seconds for connecting to the server.
"checkServer" boolean FALSE Whether to check if we can connect to the server when starting container.

Auth_Container_LDAP

Auth_Container_LDAP – Authenticate against an LDAP server

LDAP Container

This storage container makes use of the ldap extension to load user data from an LDAP server.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"host" string "localhost" The host name or IP-adress to access
"port" integer 389 The port of the LDAP server to access
"url" string " A fully qualified URL for specifying the protocol, url and port to connect to. It is useful for specifying ldaps://. Takes precedence over "host" and "port" options. Only works if PHP has been compiled against OpenLDAP 2+ libraries.
"version" integer 2 LDAP version to use, usually 2 (default) or 3, must be an integer!
"referrals" boolean TRUE If set, determines whether the LDAP library automatically follows referrals returned by LDAP servers or not.
"binddn" string " If set, searching for user will be done after binding as this user, if not set the bind will be anonymous. This is reported to make the container work with MS Active Directory, but should work with any server that is configured this way. This has to be a complete dn for now (basedn and userdn will not be appended).
"bindpw" string " The password to use for binding with binddn.
"basedn" string " The base DN of your server.
"userdn" string " Gets prepended to basedn when searching for users.
"userscope" string "sub" Scope for user searching: one, sub (default), or base.
"userattr" string "uid" Defines the attribute to search for.
"userfilter" string "(objectClass=posixAccount)" Filter that will be added to the search filter this way: (&(userattr=username)(userfilter)).
"attributes" array array('') Array of additional attributes to fetch from entry. These will added to auth data and can be retrieved via Auth::getAuthData() . An empty array will fetch all attributes, array('') will fetch no attributes at all (default). If you add 'dn' as a value to this array, the user's DN that was used for binding will be added to auth data as well.
"attrformat" string "AUTH"

The returned format of the additional data defined in the 'attributes' option. Two formats are available.

LDAP returns data formatted in a multidimensional array where each array starts with a 'count' element providing the number of attributes in the entry, or the number of values for attributes. When set to this format, the only way to retrieve data from the Auth object is by calling getAuthData('attributes'). This was the default format before version 1.3.0.

AUTH returns data formatted in a structure more compliant with other Auth Containers, where each attribute element can be directly called by getAuthData() method from Auth. This became the default as of 1.3.0.

"groupdn" string " Gets prepended to basedn when searching for group.
"groupattr" string "cn" The group attribute to search for.
"groupfilter" string "(objectClass=groupOfUniqueNames)" Filter that will be added to the search filter when searching for a group: (&(groupattr=group)(memberattr=username)(groupfilter)).
"memberattr" string "uniqueMember" The attribute of the group object where the user dn may be found.
"memberisdn" boolean TRUE Whether the memberattr is the dn of the user (default) or the value of userattr (usually uid).
"group" string " The name of the group users have to be a member of to authenticate successfully.
"groupscope" string "sub" Scope for group searching: one, sub (default), or base.
"start_tls" boolean "false" Enable/disable the use of START_TLS encrypted connection.
"try_all" boolean FALSE If multiple entries are returned by the search attempt to authenticate against each entry in order or just the first one (default).
"debug" boolean FALSE Enable debug output.

Authenticating against a LDAP server

<?php
$a1 = new Auth("LDAP", array(
   'host' => 'localhost',
   'port' => '389',
   'version' => 3,
   'basedn' => 'o=netsols,c=de',
   'userattr' => 'uid',
   'binddn' => 'cn=admin,o=netsols,c=de',
   'bindpw' => 'password'
   ));
?>

Requiring users to be within specific groups

<?php
$a2 = new Auth('LDAP', array(
   'url' => 'ldaps://ldap.netsols.de',
   'basedn' => 'o=netsols,c=de',
   'userscope' => 'one',
   'userdn' => 'ou=People',
   'groupdn' => 'ou=Groups',
   'groupfilter' => '(objectClass=posixGroup)',
   'memberattr' => 'memberUid',
   'memberisdn' => false,
   'group' => 'admin'
   ));
?>

Authenticating against a Microsoft Active Directory server

<?php
$a3 = new Auth('LDAP', array(
   'host' => 'ldap.netsols.de',
   'port' => 389,
   'version' => 3,
   'referrals' => false,
   'basedn' => 'dc=netsols,dc=de',
   'binddn' => 'cn=Jan Wagner,cn=Users,dc=netsols,dc=de',
   'bindpw' => 'password',
   'userattr' => 'samAccountName',
   'userfilter' => '(objectClass=user)',
   'attributes' => array(''),
   'group' => 'testing',
   'groupattr' => 'samAccountName',
   'groupfilter' => '(objectClass=group)',
   'memberattr' => 'member',
   'memberisdn' => true,
   'groupdn' => 'cn=Users',
   'groupscope' => 'one',
   ));
?>

When talking to a Microsoft ActiveDirectory server you have to use 'samaccountname' as the 'userattr' and follow special rules to translate the ActiveDirectory directory names into 'basedn'. The 'basedn' for the default 'Users' folder on an ActiveDirectory server for the ActiveDirectory Domain (which is not related to its DNS name) "win2000.example.org" would be: "CN=Users, DC=win2000, DC=example, DC=org" where every component of the domain name becomes a DC attribute of its own. If you want to use a custom users folder you have to replace "CN=Users" with a sequence of "OU" attributes that specify the path to your custom folder in reverse order. So the ActiveDirectory folder "win2000.example.org\Custom\Accounts" would become "OU=Accounts, OU=Custom, DC=win2000, DC=example, DC=org"

It seems that binding anonymously to an Active Directory is not allowed, so you have to set binddn and bindpw for user searching.

LDAP Referrals need to be set to false for AD to work sometimes.

Note also that if you want an encrypted connection to an MS LDAP server, then, on your webserver, you must specify "TLS_REQCERT never" in /etc/ldap/ldap.conf or in the webserver user's ~/.ldaprc (which may or may not be read depending on your configuration).

Auth_Container_MDB

Auth_Container_MDB – Authenticate against a database using MDB

MDB Container

This container makes use of PEAR::MDB abstraction layer for database access. That means that you can use all databases that are supported by the MDB abstraction layer to store the login data.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"dsn" string " A valid and well-formed DSN .
"table" string "auth" The name of the database table, where the authorization data is stored.
"usernamecol" string "username" The name of the column, where the username is stored
"passwordcol" string "password" The name of the column, where the crypted password is stored.
"db_fields" array array() An array of extra fields to retrieve when loading the user details.
"cryptType" string "md5" The encryption type the password is stored in.
"auto_quote" boolean TRUE Whether to enable automatic quoting of database table and field names.
"db_options" array array() An array of options to be passed to the PEAR::MDB constructor. See PEAR::MDB for more information.
"db_where" string " A string to be appended to the WHERE clause of queries against the database. It is appended to the queries used in fetchData(), listUsers(), removeUser() and changePassword(). Available since Auth 1.5.0.

Auth_Container_MDB2

Auth_Container_MDB2 – Authenticate against a database using MDB2

MDB2 Container

This container makes use of PEAR::MDB2 abstraction layer for database access. That means that you can use all databases that are supported by the MDB2 abstraction layer to store the login data.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"dsn" string " A valid and well-formed DSN .
"table" string "auth" The name of the database table, where the authorization data is stored.
"usernamecol" string "username" The name of the column, where the username is stored
"passwordcol" string "password" The name of the column, where the crypted password is stored.
"db_fields" array array() An array of extra fields to retrieve when loading the user details.
"cryptType" string "md5" The encryption type the password is stored in.
"auto_quote" boolean TRUE Whether to enable automatic quoting of database table and field names.
"db_options" array array() An array of options to be passed to the PEAR::MDB2 constructor. See PEAR::MDB2 for more information.
"db_where" string " A string to be appended to the WHERE clause of queries against the database. It is appended to the queries used in fetchData(), listUsers(), removeUser() and changePassword(). Available since Auth 1.5.0.

Note

By default, MDB2's default portability setting of MDB2_PORTABILITY_ALL is used. This setting may cause unexpected behaviour, such as field names being converted to lowercase regardless of their definition in the database schema. The "db_options" option can be used to override this, as shown in the following example.

Example overriding MDB2's default portability

<?php
$options = array('dsn'         => 'mysql://user:password@localhost/database',
                 'usernamecol' => 'UserName',
                 'passwordcol' => 'PassWord',
                 'db_options'  => array('portability' => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE)
                );
$auth = new Auth('MDB2', $options, 'loginFunction');
?>

Auth_Container_Multiple

Auth_Container_Multiple – Authenticate against multiple Auth_Containers

Multiple

This container provides a facility to attempt to authenticate against multiple Auth_Containers in order.

If a container's getAuthData() returns true Auth_Container_Multiple will return true.

When a container's getAuthData() returns false Auth_Container_Multiple will continue on through the list of available containers until a successful login is found or the list of containers is expired.

On receipt of an error from getAuthData() Auth_Container_Multiple will abort checking further containers and return the error.

The storage-specific argument for the Auth constructor() is an array of container configurations. Each container configuration has the following options:

Available Options
Option Data Type Default value Description
"type" string " The type of container to instanciate. This is the same value as used in the first parameter of the Auth constructor() .
"options" array array() This is the standard array of options required for the container.

Example usage of Auth_Container_Multiple

<?php
require_once "Auth.php";
require_once 'Log.php';
require_once 'Log/observer.php';

// Callback function to display login form
function loginFunction($username = null, $status = null, &$auth = null)
{
    /*
     * Change the HTML output so that it fits to your
     * application.
     */
    echo "<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">";
    echo "Username: <input type=\"text\" name=\"username\"><br/>";
    echo "Password: <input type=\"password\" name=\"password\"><br/>";
    echo "<input type=\"submit\">";
    echo "</form>";
}

class Auth_Log_Observer extends Log_observer {

    var $messages = array();

    function notify($event) {

        $this->messages[] = $event;

    }

}

$options = array(
    'enableLogging' => true,
    array(
        'type' => 'Array',
        'options' => array(
            'cryptType' => 'md5',
            'users' => array(
                'guest' => md5('password'),
            ),
        ),
    ),
    array(
        'type' => 'Array',
        'options' => array(
            'cryptType' => 'md5',
            'users' => array(
                'admin' => md5('password'),
            ),
        ),
    ),
);
$a = new Auth("Multiple", $options, "loginFunction");

$infoObserver = new Auth_Log_Observer(PEAR_LOG_INFO);

$a->attachLogObserver($infoObserver);

$debugObserver = new Auth_Log_Observer(PEAR_LOG_DEBUG);

$a->attachLogObserver($debugObserver);

$a->start();

if ($a->checkAuth()) {
    /*
     * The output of your site goes here.
     */
    print "Authentication Successful.<br/>";
}

print '<h3>Logging Output:</h3>'
    .'<b>PEAR_LOG_INFO level messages:</b><br/>';

foreach ($infoObserver->messages as $event) {
    print $event['priority'].': '.$event['message'].'<br/>';
}

print '<br/>'
    .'<b>PEAR_LOG_DEBUG level messages:</b><br/>';

foreach ($debugObserver->messages as $event) {
    print $event['priority'].': '.$event['message'].'<br/>';
}

print '<br/>';
?>

Note

This container has only been available since version 1.5.0.

Auth_Container_PEAR

Auth_Container_PEAR – Authenticate against the PEAR website

PEAR Container

This container provides authentication services against the PEAR website (http://pear.php.net/) and the developer accounts. The HTTP_Client package must be installed for this container to operate, as of Auth 1.5.3.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"url" string "https://pear.php.net/rest-login.php/" The base URL of a PEAR website to authenticate against.
"karma" array array() List of karma levels required for a valid authentication. If no karma levels are supplied than simply validating the username and password will result in success.

Auth_Container_POP3

Auth_Container_POP3 – Authenticate against a POP3 server

POP3 Container

This storage container connects to the specified POP3 server and tries to login there with the specified username/password.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"host" string "localhost" The hostname or IP address of the POP3 server.
"port" integer "110" The port number the POP3 server is listening on.
"method" boolean or string TRUE

The authentication method to use with the POP3 server. Available options:

TRUE

Use Net_POP3's autodetection algorithm.

'DIGEST-MD5', 'CRAM-MD5', 'LOGIN', 'PLAIN', 'APOP', 'USER'

Attempt this authentication style first then fallback to autodetection.

Auth_Container_RADIUS

Auth_Container_RADIUS – Authenticate against a RADIUS server

RADIUS Container

You need Auth_RADIUS and the PECL radius in order to get this container to work.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"servers" array array("localhost", 0, "testing123", 3, 3)

Array of RADIUS servers, containing: host, port, shared secret, timeout, maxtries.

The host parameter specifies the server host, either as a fully qualified domain name or as a dotted-quad IP address in text form.

The port parameter specifies the UDP port to contact on the server. If port is given as 0, the library looks up the radius/udp entry in the network services database, and uses the port found there. If no entry is found, the library uses the standard RADIUS port for authentication (1812).

The shared secret for the server host is passed to the secret parameter. The RADIUS protocol ignores all but the leading 128 bytes of the shared secret.

The timeout for receiving replies from the server is passed to the timeout parameter, in units of seconds.

The maximum number of repeated requests to make before giving up is passed into the maxtries parameter.

At most 10 servers may be specified. When multiple servers are given, they are tried in round-robin fashion until a valid response is received, or until each server's maxtries limit has been reached.

"authtype" string "PAP"

The authentication method for validating the request. Possible values are: PAP, CHAP_MD5, MSCHAPv1, MSCHAPv2.

There are dependencies for the different methods. For all authentication methods except PAP you need the Crypt_CHAP package, when you are using MS-CHAP you need also the mhash extension.

Auth_Container_SAP

Auth_Container_SAP – Authenticate against a SAP server

SAP Container

This container allows authentication against a SAP server using the SAPRFC extension available at http://saprfc.sourceforge.net/.

The storage-specific argument for the Auth constructor() is an array of options which are passed directly to the SAPRFC extension. None of the options are used internally, for more details see the SAPRFC's documentation.

Auth_Container_SMBPasswd

Auth_Container_SMBPasswd – Authenticate a SAMBA smbpasswd file using File_SMBPasswd

SMBPasswd Container

This storage container provides authentication against SAMBA smbpasswd files. It makes use of the PEAR File_SMBPasswd package.

The storage-specific argument for the Auth constructor() is a string containing the filename of the SAMBA smbpasswd file to use.

Auth_Container_SOAP

Auth_Container_SOAP – Authenticate against a SOAP service

SOAP Container

This container makes use of the PEAR SOAP client to provide authentication against a SOAP service.

The storage-specific argument for the Auth constructor() is an array of options.

Available Options
Option Data Type Default value Description
"endpoint" string   The URI where the service is located.
"namespace" string   The namespace of the web service.
"method" string   The SOAP method you wish to call.
"encoding" string   The content encoding that should be used (e.g. UTF-8).
"usernamefield" string   The name of the field where the username is stored.
"passwordfield" string   The name of the field where the password is stored.
"matchpasswords" boolean TRUE

If TRUE then the container will look for the password field in the returned result from the soap call and try to match that value with the one supplied from the end user.

If FALSE then it is assumed that the soap call will return an error if the user does not authenticate properly. If no error is returned than the user is assumed to valid and allowed to proceed.

"_features" array  

A named array of extra parameters that are to be passed to the soap call in addition to the username and password fields. These are passed to the soap call as named parameters.

<?php
array(
  'field1'  => 'value1',
  'foo'     => 'bar',
);
?>

Auth_Container_SOAP5

Auth_Container_SOAP5 – Authenticate against a SOAP service

SOAP5 Container

This container makes use of the PHP SOAP extension's client to provide authentication against a SOAP service.

The storage-specific argument for the Auth constructor() is an array of options. In addition to the below options all options for the PHP SOAP Client can be passed in this array and they will be passed onto the client.

Available Options
Option Data Type Default value Description
"wsdl" string   The location of the WSDL file describing the SOAP service you wish to authenticate against. The WSDL file takes priority over a specified "location" and "uri".
"location" string   The URI where the service is located, when not making use of a WSDL file.
"uri" string   The namespace of the web service, when not making use of a WSDL file.
"method" string   The SOAP method you wish to call.
"usernamefield" string "username" The name of the field where the username is stored.
"passwordfield" string "password" The name of the field where the password is stored.
"matchpasswords" boolean TRUE

If TRUE then the container will look for the password field in the returned result from the soap call and try to match that value with the one supplied from the end user.

If FALSE then it is assumed that the soap call will return an error if the user does not authenticate properly. If no error is returned than the user is assumed to valid and allowed to proceed.

"_features" array  

A named array of extra parameters that are to be passed to the soap call in addition to the username and password fields. These are passed to the soap call as named parameters.

<?php
array(
  'field1'  => 'value1',
  'foo'     => 'bar',
);
?>

Auth_Container_vpopmail

Auth_Container_vpopmail – Authenticate against a vpopmail service

vpopmail Container

This container uses an existing vpopmail service to validate the username and the password.

It does not require any storage-specific argument.

Custom Auth_Container

Custom Auth_Container – Build a custom storage container

Custom Storage Containers

Here is a skeleton for a custom Auth storage container

CustomAuthContainer.php

<?php
include_once 'Auth/Container.php';

class CustomAuthContainer extends Auth_Container
{
    /**
     * Constructor
     */
    function CustomAuthContainer($params)
    {
      // Init Here
    }

    function fetchData($username, $password)
    {
        // Check If valid etc
        if($isvalid) {
            // Perform Some Actions
            return true;
        }
        return false;
    }
}
?>

And here is how to use it.

authcustom.php

<?php
include_once 'CustomAuthContainer.php';
include_once 'Auth/Auth.php';

$auth_container = new CustomAuthContainer($params);
$myauth = new Auth($auth_container);

$myauth->start();
?>

Auth_Frontend_HTML

Auth_Frontend_HTML – Default login form

Overview

PEAR::Auth_Frontend_HTML provides a generic default login page for use with PEAR::Auth. When building your own login page it is a reasonable place to start as it includes all the required elements of the login form.

Constants

Constants – predefined constants

AUTH_IDLED

-1

Returned if a session exceeds its idle time.

AUTH_EXPIRED

-2

Returned if a session has expired.

AUTH_WRONG_LOGIN

-3

Returned if the Auth Container in use is unable to validate the username/password pair supplied.

AUTH_METHOD_NOT_SUPPORTED

-4

Returned if the requested function is not implemented by the Auth Container in use.

AUTH_SECURITY_BREACH

-5

Returned if the advanced security checking detects a breach.

AUTH_CALLBACK_ABORT

-6

Returned if the checkAuth callback function aborted the session.

Auth::Auth()

Auth::Auth() – constructor

Synopsis

Auth::Auth ( mixed $storageDriver , mixed $options = "" , string $loginFunction = "" , boolean $showLogin = true )

Description

Constructor for the authentication system.

The constructor will ensure that the PHP session management is started by calling session_start(). This is done as Auth requires a session to be active to operate correctly.

Parameter

string $storageDriver

Name of the storage driver that should be used, alternatively you can pass a custom Auth_Container object.

mixed $options

Array containing the options for both Auth itself and the storage driver. See Auth Options for global options and each storage driver's documentation for specific options.

string $loginFunction

The name of a user-defined function that prints the login screen. This function is passed three parameters when called $username, $status, &$auth. These are in order the previously attempted username, the status code that caused the previous auth attempt to fail and a reference to the Auth object itself.

boolean $showLogin

Defines if the login is optional or not.

Note

This function can not be called statically.

See

Introduction - The storage drivers

Example

Using different DB parameters

<?php
require_once "Auth/Auth.php";

function myOutput($username, $status, $auth)
{
    ...  /* See first example in introduction for the full listing */
}

$params = array(
            "dsn" => "mysql://martin:test@localhost/auth",
            "table" => "myAuth",
            "usernamecol" => "myUserColumn",
            "passwordcol" => "myPasswordColumn"
            );

$a = new Auth("DB", $params, "myOutput");

$a->start();

if ($a->getAuth()) {
    echo "You have been authenticated successfully.";
}
?>

This example shows you how you can specifiy alternative names for the database table and the column names. In our example, we use the table myAuth, select the username from the field myUserColumn and the password from the field myPasswordColumn. The default values for this fields are auth, username and password. Note that you can also specify an existing DB object with the dsn parameter instead of a DSN.

This feature is necessary if you want to use PEAR::Auth with a database layout that is different from the one PEAR::Auth uses by default.

Example

Using different DB parameters

<?php
require_once "Auth/Auth.php";

function myOutput($username, $status)
{
    ...  /* See first example in introduction for the full listing */
}

$a = new Auth(new CustomAuthContainer($options), null, "myOutput");

$a->start();

if ($a->getAuth()) {
    echo "You have been authenticated successfully.";
}
?>

This example shows you how you can pass your own storage container to Auth.

If the storage containers supplied with Auth are not capable of fulfilling your requirements, you can easliy create your own storage container. Read the storage containers section for more info Introduction - The storage drivers

Auth::addUser()

Auth::addUser() – add a new user

Synopsis

mixed Auth::addUser ( string $username , string $password , mixed $additional = '' )

Description

Add a new user to the Auth Container.

Parameter

string $username

the username of the new user

string $password

the password of the new user

mixed $additional = ''

additional options to be passed to the creation of the new user. Each Auth_Container has different options for these, please see the containers documentation for what is supported.

Return value

mixed - TRUE on success, a PEAR Error on failure.

Note

This function can not be called statically.

Not all Auth Containers implement this functionality.

Auth::attachLogObserver()

Auth::attachLogObserver() – Attach a log observer instance to the internal Log object

Synopsis

void Auth::attachLogObserver ( object &$observer )

Description

Attach an instance of a Log_Observer to the internal Log object. This allows the internal logs to be accessed and used as you wish within your application.

Parameter

object &$observer

The instance of the Log_Observer to attach to the internal Log object.

Note

This function can not be called statically.

This function has only been available since version 1.5.0.

Auth::changePassword()

Auth::changePassword() – change the password of a user

Synopsis

mixed Auth::changePassword ( string $username , string $password )

Description

Change the password of a user within the Auth Container.

Parameter

string $username

the username of the user

string $password

the new password for the user

Return value

mixed - TRUE on success, a PEAR Error on failure.

Note

This function can not be called statically.

Not all Auth Containers implement this functionality.

Auth::checkAuth()

Auth::checkAuth() – check if a session with valid authentication information exists

Synopsis

boolean Auth::checkAuth ( )

Description

Checks if a session exists that contains valid authentication information.

Return value

boolean - If a session with valid authentication information exists, the function return TRUE. Otherwise it returns FALSE.

Note

This function can not be called statically.

Auth::getAuth()

Auth::getAuth() – check for an authenticated user

Synopsis

boolean Auth::getAuth ( )

Description

Check if the user has been authenticated.

In previous versions, this function had a different behaviour than Auth::checkAuth()(). Now it is just an alias for Auth::checkAuth()().

Return value

boolean - If the user has already been authenticated, the function returns TRUE. Otherwise it returns FALSE.

Note

This function can not be called statically.

Auth::getAuthData()

Auth::getAuthData() – retrieve extra information stored within the auth session

Synopsis

mixed Auth::getAuthData ( string $name )

Description

This function retrieves the value of a previously registered data field.

Parameter

string $name

the name of the data field

Note

This function can not be called statically.

Auth::getStatus()

Auth::getStatus() – get the current status of the auth session

Synopsis

int Auth::getStatus ( )

Description

Get the current status of the authentication session.

Return value

int - An Auth constant representing the current session state.

Note

This function can not be called statically.

See

"Auth Constants".

Auth::getUsername()

Auth::getUsername() – get the username of the authenticated user

Synopsis

string Auth::getUsername ( )

Description

Get the username of the logged in user.

Return value

string - The username of the logged in user.

Note

This function can not be called statically.

Auth::listUsers()

Auth::listUsers() – list available users

Synopsis

array Auth::listUsers ( )

Description

List all the users currently available within the current Auth Container.

Return value

array - An array of user details. Currently no consistency, see each Auth Container for details on how and what they return.

Note

This function can not be called statically.

Not all Auth Containers implement this functionality.

Auth::logout()

Auth::logout() – logout an authenticated user

Synopsis

void Auth::logout ( )

Description

Logout any currently logged in user.

Example

<?php
//$a is our Auth object
$a->start();

if (isset($_GET['action']) && $_GET['action'] == 'logout'
    && $a->checkAuth()
) {
    $a->logout();
    $a->start();
}
?>

Auth::removeUser()

Auth::removeUser() – remove a user account

Synopsis

mixed Auth::removeUser ( string $username )

Description

Remove a user from the Auth Container.

Parameter

string $username

the username of the user to remove

Return value

mixed - TRUE on success, a PEAR Error on failure.

Note

This function can not be called statically.

Not all Auth Containers implement this functionality.

Auth::setAdvancedSecurity()

Auth::setAdvancedSecurity() – Enables advanced security features. Turned off by default

Synopsis

void Auth::setAdvancedSecurity ( mixed $flag = true )

Description

Enables advanced security features to make man in the middle attacks and session hijacking much harder. Cookies and java script must be enabled on the client browser for some of these features to function correctly.

Enables the following security features of auth

This method is available since 1.3.0

Parameter

mixed $flag

TRUE if you want to enable advanced security features FALSE if you want to disable them.

You also may pass an array if you want to fine-tune security options. TRUE means the following:

<?php
array(
    AUTH_ADV_USERAGENT => true,
    AUTH_ADV_IPCHECK   => true,
    AUTH_ADV_CHALLENGE => true
);
?>

Note

This function can not be called statically.

Auth::setAllowLogin()

Auth::setAllowLogin() – Controls if the user will be allowed to login. Turned on by default

Synopsis

void Auth::setAllowLogin ( bool $allowLogin = true )

Description

Controls if auth will process the post variables and attempt to login the user from those pages. For better security of your application it is recomended to disable login in all pages except your login page.

Parameter

boolean $allowLogin

If you want to allow login set this to TRUE otherwise set it to FALSE.

Note

This function can not be called statically.

This method is available since 1.3.0

Auth::setAuth()

Auth::setAuth() – set a specific user to be marked as logged in

Synopsis

void Auth::setAuth ( string $username )

Description

Mark the session up to indicate that the username supplied has successfully logged in. Although normally used for internal purposes this function can be used to fake a login.

Parameter

string $name

the name of the data field

Note

This function can not be called statically.

This function will also call session_regenerate_id() so as to prevent session fixation attacks.

Auth::setAuthData()

Auth::setAuthData() – store extra information with the Auth session

Synopsis

void Auth::setAuthData ( string $name , mixed $value , boolean $overwrite = true )

Description

This function allows the registration of extra information to be stored allowing with the authentication data.

Parameter

string $name

the name of the data field

mixed $value

the value of the data field

boolean $overwrite

whether to overwrite the value of the data field if it already exists.

Note

This function can not be called statically.

Auth::setCheckAuthCallback()

Auth::setCheckAuthCallback() – set a callback to run when ever session validity is checked

Synopsis

void Auth::setCheckAuthCallback ( string $checkAuthCallback )

Description

This function sets a callback function which is called whenever the validity of a logged in session is checked. This callback can be used to perform actions like checking the authentication source to see if the logged in user is still enabled.

The callback function will be passed two parameters, the username that successfully logged in and a reference to the Auth object. The callback function should return a boolean depending upon whether the session should continue or not. TRUE to allow the session to continue, FALSE to abort the session.

If the session is aborted by this callback the status will be set to AUTH_CALLBACK_ABORT.

Parameter

string $checkAuthCallback

the call back function to use

Note

This function can not be called statically.

Auth::setExpire()

Auth::setExpire() – set expiration time for authentication

Synopsis

void Auth::setExpire ( integer $time , boolean $add = false )

Description

With this function you can set the maximum expire time that is used by auth to a new value.

Parameter

integer $time

expiration time, number of seconds

boolean $add

if TRUE $time is added to the existing expiration time, if FALSE the exitsing time value will be replaced.

Note

This function can not be called statically.

Auth uses PHP's session mechanism to recognize users between http calls. Setting Auth's expiry time larger than the session timeout will still expire the session to the time the php session expires.

Auth::setFailedLoginCallback()

Auth::setFailedLoginCallback() – set a callback for failed login attempts

Synopsis

void Auth::setFailedLoginCallback ( string $loginFailedCallback )

Description

This function sets a callback function which is called upon failed login of a user account.

The callback function will be passed two parameters, the username that failed to login and a reference to the Auth object.

Parameter

string $loginFailedCallback

the call back function to use

Note

This function can not be called statically.

Auth::setIdle()

Auth::setIdle() – set maximum idle time for authentication

Synopsis

void Auth::setIdle ( integer $time , boolean $add = false )

Description

With this function one can set the maximum idle time to a new value. The term "idle time" describes the maximum time interval (in seconds) between two actions by the user. If the maximum idle time is reached, the user will be automatically logged out. If on the other hand the user performs any action within the maximum idle time interval, the idle time is reset.

Parameter

integer $time

idle time in seconds

boolean $add

if TRUE $time is added to the existing idle time, if FALSE the existing time value will be replaced.

Note

This function can not be called statically.

Auth::setLoginCallback()

Auth::setLoginCallback() – set a callback for successful login attempts

Synopsis

void Auth::setLoginCallback ( string $loginCallback )

Description

This function sets a callback function which is called upon successful login of a user account.

The callback function will be passed two parameters, the username that successfully logged in and a reference to the Auth object.

Parameter

string $loginCallback

the call back function to use

Note

This function can not be called statically.

Auth::setLogoutCallback()

Auth::setLogoutCallback() – set a callback for successful logout attempts

Synopsis

void Auth::setLogoutCallback ( string $loginCallback )

Description

This function sets a callback function which is called upon successful logout of a user account.

The callback function will be passed two parameters, the username that successfully logged out and a reference to the Auth object.

Parameter

string $loginCallback

the call back function to use

Note

This function can not be called statically.

Auth::setSessionName()

Auth::setSessionName() – set a custom name for the Auth session variable

Synopsis

void Auth::setSessionName ( string $name )

Description

This function is used to set the name of the session variable used to store the user's authentication details. The default for the session variable name is _authsession.

Parameter

string $name

the session variable name to use

Note

This function can not be called statically.

You have to use setSessionName(), if you are running two or more different applications with Auth on the same domain. If you don't use this function, a user who has once logged in at one of the applications can also use the other applications without logging in again!

Auth::setShowLogin()

Auth::setShowLogin() – controls if the login form will be displayed. Turned on by default

Synopsis

void Auth::setShowLogin ( bool $showLogin = true )

Description

Controls if the login page will be displayed to the user. Normally you might need to display the login form only on a certain page of your web application.

Parameter

boolean $showLogin

true if you want to display the login form and false if you want to hide it.

Note

This function can not be called statically.

This is equivalent to the 4th paramether of Auth::Auth()

Auth::sessionValidThru()

Auth::sessionValidThru() – get the time up to the session is valid

Synopsis

void Auth::sessionValidThru ( )

Description

This method returns the time in seconds after which the idle time of the current authentication session has reached its limit, which will cause the user to be logged out automatically. If no maximum idle time is set, which is the default configuration of PEAR::Auth, this method will return 0.

Note

This function can not be called statically.

Auth::start()

Auth::start() – start authentication

Synopsis

void Auth::start ( )

Description

Start the authentication process. To do this Auth checks for an existing session and checks its validity. If there is no existing session or the previous session has been ended for some reason then the login form is generated either via the specified callback or using the default form implemented in Auth_Frontend_HTML.

Note

This function can not be called statically.