« Return

Login authentication with PEAR extension

MySQL table structure
CREATE TABLE auth (
username VARCHAR(50) default '' NOT NULL,
password VARCHAR(32) default '' NOT NULL,
PRIMARY KEY (username),
KEY (password)
)
config.php
<?php
require_once('Auth.php'); // make sure PEAR Auth package is installed. http://pear.php.net/package/Auth

function show_login_form() {
echo  '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">
      username <input type="text" name="username" />
      password <input type="password" name="password" />
      <input type="submit" value="Login" />
      </form>';
}

$db_auth      = 'database_name';    // database for authentication
$db_server    = 'localhost';        // database server, usually "localhost"
$db_user      = 'username';         // database username
$db_pass      = 'password';         // database password

$options      = array('dsn' => 'mysql://' .$db_user. ':' .$db_pass. '@' .$db_server. '/' .$db_auth.'');
$auth         = new Auth('DB', $options, 'show_login_form');

/* to create a new user, run this script ONCE - password is md5() hash */
// $auth->addUser('username', 'password');
?>
login.php
<?php
require ('config.php');
$auth->start(); // start the authorization

if ($auth->checkAuth()) {
        echo '<p>You are now logged in.</p>
              <p><a href="logout.php">click to logout</a></p>';
} else {
        echo '<p>You must be logged in to access this page.</p>';
}
?>
logout.php
<?php
require ('config.php');
$auth ->start();

if ($auth->checkAuth()) {
    $auth->logout();
    $auth->start();
}
?>