采用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