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 (Previous) Options for controlling the behaviour of Auth (Next)
Last updated: Wed, 17 Sep 2014 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report or add a note.
View this page in:

User Notes:

Note by: marty@pagemiller.com
In the mini-tutorial, there is a section on optional authentication.

The var named $optional should be renamed $required.

The way the demo works, if $optional is true and is used as the fourth parameter, then login is required.

If you named the fourth parameter $required, and if it was false, login would not be required.

The variable name would make more sense to be named $required. Because if it is false, login is not required.

Just my $.02.
Note by: Happy_User
To Frustrated_User:

You're lack of using the Log functions is likely the only problem you have. I had the same issue as you. I turned on the Logging and voila! There was the problem!

(My table name was "Auth" and it was trying to use "auth" -- duh!)
Note by: Frustrated_User
Somehow I think your documentation lacks some essential points, I just get status -3 all the time (authentication failure), the database connection seems to work when I look at the print_r output from the Auth object. I don't get any error messages from the class nor from PHP itself, great job on making debugging easy, my compliments to you (and no, I don't want to use the PEAR::Log class, thanks).

The least thing you guys should do is update the example to use MDB2 instead of DB, I mean come on - how hard is that?? That's obviously the first thing everybody stumbles across.
Note by: niklas@...
A quick FYI for people who want to use the Auth package in a class and use a custom login function. Take the following example:

You have your userclass from which you call the Auth package. You want to use a function from your class as a custom login handler.

Auth.php uses PHPs is_callable to check if the function exists so it might be good to read up on http://php.net/manual/en/function.is-callable.php

The login-function variable can take an array if you need to call a certain class:

array($classreference, 'yourfunction')

I.e:

array($this, "loginFunction")

Or:

new Auth('MDB2', $this->options, array($this, "loginFunction"), $forcelogin);
Note by: chris@tactek.com
Not to be contrary, but the statement in the documentation that "...the MD5 algorithm...is the default encryption..." is a misnomer. Hashing is not encryption. Googling for "hashing is not encryption" will return numerous articles on this common misconception.
Note by: compufreak.info
ts@websafe.pl asked:

Isn't there an error?

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

right after /database", the comma is not needed, or am I wrong?

-----------------------

This is correct. The comma is not needed. But it is perfectly 'legal'! You may add a Comma after the last array-element. only, because if you add more elements, you won't forget the comma between the old element and the first new element. it will work and it is okay!
Note by: cronimson@yahoo.com
example does not work and i have in the internet for examples and all of them does not work also. can someone post a working sample.. this is frustrating.
Note by: wiesemann
@shelleykm..., please use the support offers on pear.php.net for asking support questions. About the usage of DB here: The example is just a little bit older. If you have suggestions about how it could be improved, please open a bug report via the link that is offered on the footer of this page (next to the link that you've used to file your user note).
Note by: wiesemann
@ts..., the comma isn't needed, that's right. But this isn't an error. PHP accepts the comma, and it makes people's life easier in some sense because you don't have to worry about adding the comma if you add another key/value pair to the $options array.
Note by: ts@websafe.pl
Isn't there an error?

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

right after /database", the comma is not needed, or am I wrong?
Note by: shelleykm@adelphia.net
Thanks to the above poster for the encryption hint. Unfortunately I don't have it working yet.

Also, why is the "DB" connector listed here? In the PEAR doc it even says DB has been deprecated in favor of MDB2. Why give newbies examples with includes that aren't recommended to use anymore?
Note by: Mario
Just adding one clarification for newbies (as I am).

If you want to test the 2 examples, don't forget that the password in your table must be encrypted.