First of all, sorry for my English.
Here are two functions to check group membership and some others which can be useful for work with LDAP (Active Directory in this example).
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('Could not connect to LDAP server.');
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('Could not bind to AD.');
$userdn = getDN($ad, $user, $basedn);
if (checkGroupEx($ad, $userdn, getDN($ad, $group, $basedn))) {
echo "You're authorized as ".getCN($userdn);
} else {
echo 'Authorization failed';
}
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;
}
?>