首先,抱歉我的英语。
以下两个函数用于检查组成员资格,以及一些其他对使用 LDAP(在本例中为 Active Directory)有用的函数。
index.php
---------
<?php
$user = 'bob';
$password = 'zhlob';
$host = 'myldap';
$domain = 'mydomain.ex';
$basedn = 'dc=mydomain,dc=ex';
$group = 'SomeGroup';
$ad = ldap_connect("ldap://{$host}.{$domain}") or die('无法连接到 LDAP 服务器。');
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ad, LDAP_OPT_REFERRALS, 0);
@ldap_bind($ad, "{$user}@{$domain}", $password) or die('无法绑定到 AD。');
$userdn = getDN($ad, $user, $basedn);
if (checkGroupEx($ad, $userdn, getDN($ad, $group, $basedn))) {
echo "您已授权为 ".getCN($userdn);
} else {
echo '授权失败';
}
ldap_unbind($ad);
function getDN($ad, $samaccountname, $basedn) {
$attributes = array('dn');
$result = ldap_search($ad, $basedn,
"(samaccountname={$samaccountname})", $attributes);
if ($result === FALSE) { return ''; }
$entries = ldap_get_entries($ad, $result);
if ($entries['count']>0) { return $entries[0]['dn']; }
else { return ''; };
}
function getCN($dn) {
preg_match('/[^,]*/', $dn, $matchs, PREG_OFFSET_CAPTURE, 3);
return $matchs[0][0];
}
function checkGroup($ad, $userdn, $groupdn) {
$attributes = array('members');
$result = ldap_read($ad, $userdn, "(memberof={$groupdn})", $attributes);
if ($result === FALSE) { return FALSE; };
$entries = ldap_get_entries($ad, $result);
return ($entries['count'] > 0);
}
function checkGroupEx($ad, $userdn, $groupdn) {
$attributes = array('memberof');
$result = ldap_read($ad, $userdn, '(objectclass=*)', $attributes);
if ($result === FALSE) { return FALSE; };
$entries = ldap_get_entries($ad, $result);
if ($entries['count'] <= 0) { return FALSE; };
if (empty($entries[0]['memberof'])) { return FALSE; } else {
for ($i = 0; $i < $entries[0]['memberof']['count']; $i++) {
if ($entries[0]['memberof'][$i] == $groupdn) { return TRUE; }
elseif (checkGroupEx($ad, $entries[0]['memberof'][$i], $groupdn)) { return TRUE; };
};
};
return FALSE;
}
?>