0

I have an issue where if I create a filter string like "(&(sAMAccountName=username))" the search works without issue, and if I use a variable that has a defined string value like $username = "username" it works, but if I make the variable equal to the contents of an array element, it fails with "Bad search filter" error.

This is the section of code that is giving me grief..

$ldap_conn = ldap_connect("ldaps://".$INFO['ldap_server'], $INFO['ldaps_port']) or die (" Failed to connect to server via LDAPS");
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, true);
$result = ldap_bind($ldap_conn, $INFO['ldaps_user'], $INFO['ldap_pswd']) or die ("Failed to BIND to server via LDAPS: ".ldap_error($ldap_conn));
$attr = array("givenName","lastLogonTimestamp","lastLogon","distinguishedName","useraccountcontrol");
$usrSRCH = $INFO['ldap_srch_ou'].','.$INFO['msad_domain'];

# Find Manager
$username =  trim($InpArry[0]);
$filter1 = "(&(sAMAccountName=".$username."))";
$result2 = ldap_search($ldap_conn, $usrSRCH, $filter1, $attr);
if ($result2) {
    $entries  = ldap_get_entries($ldap_conn, $result2);
    $recCNT = ldap_count_entries($ldap_conn, $result2);
} else echo '(Mgr)-LDAP Error: [' . ldap_errno($ldap_conn) . '] ' . ldap_error($ldap_conn) . '<br>';

Any help would be appreciated..

James4U
  • 1
  • 1
  • The first thing is that you don't need the `&` operator since you have only one condition : `$filter1 = "(sAMAccountName=".$username.")";`. If you still have the error, check if the actual value of `$username` is what you expect. Also, you need to escape that string because it may contain special characters, which could cause this specific error. See this [post](https://stackoverflow.com/a/39805523/2529954) for more info about how to escape ldap special characters. – EricLavault Nov 11 '21 at 12:05
  • Thanks for the info.. The post on escape chars for LDAP was very helpful.. By striping the variable of null character, it worked.. Thanks for your help.. For anyone else caught in this delema, this is the code I added to remove the nuls `$username = str_replace("\0", "",trim($InpArry[0]));` – James4U Nov 11 '21 at 16:53

0 Answers0