采用PHP PEAR中的AUTH实现基本身份验证
所需文件:
PEAR DB,Auth
表结构
CREATE TABLE auth (
username VARCHAR(50) default '' NOT NULL,
password VARCHAR(32) default '' NOT NULL,
PRIMARY KEY (username),
KEY (password)
);
代码:
<?php
require_once "Auth/Auth.php";
function loginFunction()
{
/**
* Change the HTML output so that it fits to your
* application.
*/
echo "<form method=/"post/" action=/"" . $_SERVER['PHP_SELF'] . "?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;
}
$dsn = "mysql://user:pass@localhost/authdb";
$a = new Auth("DB", $dsn, "loginFunction", $optional);
$a->start();
if (! isset($_GET['login'])) {
echo "<a href=/"" . $_SERVER['PHP_SELF'] . "?login=1/">Click here to log in</a><br />/n";
}
if ($a->getAuth()) {
//add some code here
echo "<a href=/"" . $_SERVER['PHP_SELF'] . "?action=logout/">Logout</a><br />/n";
} elseif($_GET['login'] == 1) {
echo "Please login";
}
//注销,重新登录
if ($_GET['action'] == "logout" && $a->getAuth()) {
$a->logout();
$a->start();
}
?>
这样一个简单的验证程序就好了,你可以自行扩展它的用户界面。
注:默认的口令加密码方式为MD5,即if (md5($_POST['password']) === password),表名和字段名不能变动,
password的字段长度最小为32
上面介绍的是通过表单FORM的方式来验证,下面介绍的是通过发送headers信息到客户端实现验证。
Auth_HTTP
<?php
require_once('Auth/Auth_HTTP.php');
//连接数据库
$options = array(
"dsn" => "mysql://user:pass@localhost/authdb",
"table" => "auth",
"usernamecol" => "username",//用户名字段
"passwordcol" => "password",//口令字段
"cryptType" => "md5", //口令加密方式,明文验证则'none'
'dbFields'=>"*", //顺便取出表中的其它字段,所有为*
);
$au = new Auth_HTTP("DB", $options);
$au->setExpire(5);
$au->setRealm("请输入认证信息:");
$au->setCancelText("<font color='red'>认证信息不正确,请确认重输</font><p><a href='/'>返回</a></p>");
$au->start();
if($au->getAuth()) {
echo($au->username);
echo("<br />");
echo($au->getAuthData('email'));
}
?>