The following example shows how to authenticate against a database.
- <?php
- require_once 'tutorial_autoload.php';
-
- $credentials = new ezcAuthenticationPasswordCredentials( 'jan.modaal', 'b1b3773a05c0ed0176787a4f1574ff0075f7521e' );
- $database = new ezcAuthenticationDatabaseInfo( ezcDbInstance::get(), 'users', array( 'user', 'password' ) );
- $authentication = new ezcAuthentication( $credentials );
- $authentication->addFilter( new ezcAuthenticationDatabaseFilter( $database ) );
- if ( !$authentication->run() )
- {
- // authentication did not succeed, so inform the user
- $status = $authentication->getStatus();
- $err = array(
- 'ezcAuthenticationDatabaseFilter' => array(
- ezcAuthenticationDatabaseFilter::STATUS_USERNAME_INCORRECT => 'Incorrect username',
- ezcAuthenticationDatabaseFilter::STATUS_PASSWORD_INCORRECT => 'Incorrect password'
- )
- );
- foreach ( $status as $line )
- {
- list( $key, $value ) = each( $line );
- echo $err[$key][$value] . "\n";
- }
- }
- else
- {
- // authentication succeeded, so allow the user to see his content
- }
- ?>
First, a credentials object is created with username jan.modaal and password
'b1b3773a05c0ed0176787a4f1574ff0075f7521e' (sha1() hash).
An authentication object is created using the credentials object, and a
Database filter is added to it. The $database structure specifies the database
instance (ezcDbInstance::get()), the table name ('users') and the username and
password fields in the table ('user', 'password').
After running the authentication (line 8), if the username and the password do
not pass through the Database filter, then the credentials are incorrect and
the user must be informed. The getStatus() method is used for this. The values
in the status returned must be cycled through and for each value a response is
created for the user ("Username incorrect", "Password incorrect").
If run() returned true (line 24) then the user is logged-in and he can see his
content.