Authentication with PEAR Auth

Abstract
PEAR offers now a session based authentication using a database container. The sample below should help you to start up with it.

Script

Links

http://pear.php.net – PEAR Repository

01  <?php

02  
/**

03  * Authentication using PEAR Auth and MySQL

04  *

05  * ———————————————————————–

06  * # Add this table to a database called \’auth\’:

07  * # Table structure for table `auth`

08  *

09  * CREATE TABLE auth (

10  * username varchar(50) default NULL,

11  * password varchar(50) default NULL

12  * ) TYPE=MyISAM COMMENT=\’PEAR, Auth\’;

13  *

14  * # Data for table `auth`, user:test, pwd:test

15  * INSERT INTO auth VALUES (\’test\’, \’098f6bcd4621d373cade4e832627b4f6\’);

16  * INSERT INTO auth VALUES (\’demo\’, \’fe01ce2a7fbac8fafaed7c982a04e229\’);

17  *

18  * ———————————————————————–

19  * Author: Urs Gehrig <urs@NOSPAMcircle.ch>

20  * Date: 2002-04-15

21  *

22  * Infos: http://pear.php.net/manual/en/packages.auth.auth.php

23  * $Id$

24  */

25  

26  
require_once(\”PEAR.php\”);

27  require_once(
\”DB.php\”);

28  require_once(
\”DB/mysql.php\”);

29  require_once(\”Auth/Auth.php\”);

30  

31  
// Initialization of database related information

32  
$params = array(

33                
\”dsn\” => \”mysql://root:@localhost/auth\”,

34                \”table\” => \”auth\”,

35                
\”usernamecol\” => \”username\”,

36                
\”passwordcol\” => \”password\”

37            );

38  

39  
// A database is used as storage container in this example

40  
$a = &new Auth(\”DB\”, $params );

41  

42  // Detection, if user is logged in. Otherwise the login form

43  // is being displayed.

44  
$a->start();

45  

46  if (
$a->getAuth())

47  {

48      if(
$_GET[act] == \”logout\”)

49      {

50          
// Log user out

51          
$a->logout();

52          echo \”You have been logged out!<br />\\n\”;

53          echo
\”<a href=\\\”$_SERVER[\’PHP_SELF\’]?act=login\\\”>Login</a><br />\\n\”;

54      }

55      else

56      {

57          
// Output the content of your site, that is only visible

58          // for users which have been authenticated successfully.

59          
printf(\”Welcome user <b>%s</b>!<br />\\n\”, $a->getUsername() );

60          echo \”<a href= \\\”$_SERVER[\’PHP_SELF\’]?act=logout\\\”>Logout</a><br />\\n\”;

61      }

62  }

63  else

64  {

65      
// Not authenticated

66      
echo \”<center>You are not authenticated.<br />\\n\”;

67      echo \”[Try: demo,demo or test,test]</center>\\n\”;

68  }

69  
?>

Leave a Reply