开发者

PHP - ldap_search() filter. How to search for user

$_SERVER['REMOTE_USER'] returns the username of the user logged in to an Active Directory. I want to retrive this users info by using ldap_search().

This is what I have now:

$ad = // ldap_connection id
$filter = "(|(sn=$username*)(givenname=$username*))";
$attr = array("displayname", "mail", "mobile", "homephone", "telephonenumb开发者_高级运维er", "streetaddress", "postalcode", "physicaldeliveryofficename", "l");
$dn = // OU, DC etc..

ldap_search($ad,$dn,$filter,$attr);

It works, but i'm not sure it will work if two users have almost the same names. How do I only search for their unique username so that i always only get one user?


sAMAccountName is the username-attribute used in Active Directory, so (&(objectClass=user)(sAMAccountName=%s)) would be the correct filter to check the LDAP for a given username (with %s being replaced by the actual username naturally).

Please be aware that you need to handle special characters in $username to avoid malformed filters or at worst malicious LDAP injections (see RFC 2254):

Any control characters with an ACII code < 32 as well as the characters with special meaning in LDAP filters "*", "(", ")", and "\" (the backslash) are converted into the representation of a backslash followed by two hex digits representing the hexadecimal value of the character.


ldap_search() will find all matching entries, you will have to verify the result. Let's say $link is your link to the LDAP database created with ldap_connect()ldap_get_entries($link, $result) You can verify that like this :

$result = ldap_search();
if(ldap_count_entries($link, $result) === 1) {
    ...
}

or

$result = ldap_search();
$entries = ldap_get_entries($link, $result);
if(sizeof($entries) === 1) {
    ...
}


ldap_search supports both and & and or |. If you want to search multiple attributes for the occurrence of your search string you can do it as follows. This will search for a person where your search string ($str) in in samaccountname or name or title.

$filter="(&(objectClass=user)(objectCategory=person)(|(sAMAccountName=*{$str}*)(name=*{$str}*)(title=*{$str}*)))";

$result=ldap_search($connection, $dn, $filter);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜