active directory – PHP – ldap_search() filter. How to search for user-ThrowExceptions

Exception or error:

$_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..


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?

How to solve:

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) {


$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.


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

Leave a Reply

Your email address will not be published. Required fields are marked *