Search code examples
phpldapldap-query

ldap_search will not accept filter with parentheses in the search input


In a php page I'm working on, an LDAP connection is established from which a list of cn entries are pulled and put into a dropdown. The selection from the dropdown is sent via form submission to another php scrips which checks the selected cn against the LDAP to grab more associated information.

For most names this is no problem; however, a cn was recently added that includes parentheses enclosing a nickname, and when that name is selected it causes the ldap_search() method to return false. Below is the code, where $employeename is the sanitized employee name.

...

$dn = "cn=users,dc=our-domain,dc=com";
$filter = "(cn=".$employeename.")";

$attrs = array("cn", "mail");
$rslt = ldap_search($ldapsvr, $dn, $filter, $attrs);

$entries = ldap_get_entries($ldapsvr, $rslt);

...

The $filter string ends up as

(cn=First (FN) Last)

where First is the first name, Last is the last name, and FN is the included nickname. I have tried escaping the parentheses as \28 and \29 (as provided here, where it also says matched parentheses do not need to be escaped), but it did not help. Names that work include letters, spaced, and periods (for middle initials).

(cn=First \28FN\29 Last)

EDIT: ldap_search is returning false, not dying. One of the lines I included while investigating would fail and die if $rslt was false and not an array.

EDIT: I escaped the inner parentheses only,. as the outer never gave any trouble


Solution

  • Try to add an operand as a sort of order-of-operations. I had a similar issue on the title field until I did similar to the following.

    $filter = "(&(cn=$employeename))";
    

    On some systems, you need to escape () with a \.

    $filter = "(&(cn=James \(Jim\) Doe))";
    

    Hang tight, working on a escape function.