CHAPTER 11 – Example: Auth with Password File

The following example shows typical Auth usage using the file container. The file container requires that you have the File_Passwd package installed. <?php require_once 'Auth.php'; $auth = new Auth("File", ".htpasswd", "login_function"); $auth->start(); if (!$auth->getAuth()) { exit; } if (!empty($_REQUEST['logout'])) { $auth->logout(); print "<h1>Logged out</h1>n"; print "<a href="$_SERVER[PHP_SELF]">Log in again</a>n"; exit; } print "<h1>Logged in!</h1>n"; if (!empty($_REQUEST['dump'])) { print "<pre>SESSION="; var_dump($_SESSION); print "</pre>n"; } else { print "<a href="$_SERVER[PHP_SELF]?dump=1">Dump session</ a><br>n"; } print "<a href="$_SERVER[PHP_SELF]?logout=1">Log Out</a>n"; // --- execution ends here --- function login_function() { print "<h1>Please Log In</h1>n"; print "<form action="$_SERVER[PHP_SELF]" method="POST">n"; print "User name: <input name="username"> "; print "Password: <input name="password"> "; print "<input type="submit" value="Log In">n"; print "</form>n"; exit; } The example password file (the username is "guest," and the password is blank) is guest:Z3kgRZpxQPbjo This example script starts by creating an Auth object using .htpasswd as a password file. The $auth->start() call sets up the PHP session (you do not need to run session_start() in advance), reads the POST variables, checks the submitted username and password, and calls login_function() if the login failed. This example script first displays a login form. After you log in as a guest (with no password), you should get two links: Dump session and Log Out.

Post Comment
Login to post comments