我正在尝试实施PHP-LDAP身份验证来验证和验证用户。我正在使用以下代码。但是,如果输入的密码不正确或域名未提供用户名(以username @ domain或domain \ username的形式),则不会出现密码提示。它始终显示“授权失败”。如果用户提供正确的用户名@ domain和密码,则可以登录。代码:
session_start();
if (strlen(@$_SERVER['PHP_AUTH_USER']) == 0 || strlen(@$_SERVER['PHP_AUTH_PW']) == 0) {
header('WWW-Authenticate: Basic realm="test"');
header('HTTP/1.0 401 Unauthorized');
echo '<h1>Authorization required</h1>';
exit;
} else {
$ldaprdn = $_SERVER['PHP_AUTH_USER'];
$ldappass = $_SERVER['PHP_AUTH_PW'];
$ldap_server = 'ldap_server_add';
$ldapconn = ldap_connect("ldap_server_add") or die("Could not connect to ".$ldap_server." server.");
$ldapbind = @ldap_bind($ldapconn, $ldaprdn, $ldappass);
if ($ldapbind) {
if (strrchr($_SERVER['PHP_AUTH_USER'], '@') || strrchr($_SERVER['PHP_AUTH_USER'], '\\')) {
if (strrchr($_SERVER['PHP_AUTH_USER'], '@')) {
$t = explode('@', $_SERVER['PHP_AUTH_USER']);
$_SESSION['userid'] = $t[0];
} else {
$t = explode('\\', $_SERVER['PHP_AUTH_USER']);
$_SESSION['userid'] = $t[1];
}
}
} else {
echo "<h1>Authorization failed</h1>";
}
}
我无法弄清楚问题。请帮帮我。
答案 0 :(得分:0)
得到了解决方案,只是一个简单的技巧,并将上面的代码更改为:
session_start();
function authenticate() {
header('WWW-Authenticate: Basic realm="test"');
header('HTTP/1.0 401 Unauthorized');
echo '<h1>Authorization required</h1>';
exit;
}
if (strlen(@$_SERVER['PHP_AUTH_USER']) == 0 || strlen(@$_SERVER['PHP_AUTH_PW']) == 0) {
authenticate();
} else {
$ldaprdn = $_SERVER['PHP_AUTH_USER'];
$ldappass = $_SERVER['PHP_AUTH_PW'];
$ldap_server = 'ldap_server_add';
$ldapconn = ldap_connect("ldap_server_add") or die("Could not connect to ".$ldap_server." server.");
$ldapbind = @ldap_bind($ldapconn, $ldaprdn, $ldappass);
if ($ldapbind) {
if (strrchr($_SERVER['PHP_AUTH_USER'], '@') || strrchr($_SERVER['PHP_AUTH_USER'], '\\')) {
if (strrchr($_SERVER['PHP_AUTH_USER'], '@')) {
$t = explode('@', $_SERVER['PHP_AUTH_USER']);
$_SESSION['userid'] = $t[0];
} else {
$t = explode('\\', $_SERVER['PHP_AUTH_USER']);
$_SESSION['userid'] = $t[1];
}
}
} else {
authenticate();
}
}