PHP - ldap_search() filter. How to search for user
Solution 1
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.
Solution 2
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) {
...
}
horgen
Updated on March 14, 2020Comments
-
horgen about 4 years
$_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", "telephonenumber", "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?