Featured image of post PHP LDAP Pagination (Solution for PHP5.4+)

PHP LDAP Pagination (Solution for PHP5.4+)

Because Active Directory restricts returning all results fetched by LDAP Query, I found a solution to get around this problem, without changing anything in Active Directory.

Because Active Directory restricts returning all results fetched by LDAP Query, I found a solution to get around this problem, without changing anything in Active Directory.

The root cause for this problem is: AD has a pagesize limit for returning elements through LDAP (default is 1000). As every good Admin / Dev knows, systemwide hardlimits should not be changed by a client system, which sends requests, because this could end up in hugh desaster. Why? Because everyone would set these limits as high as he can to prevent his software from crashing itself (better burn server cpu)

That means, we can’t set any pagelimit in PHP above the pagelimit from the server. What we need to do is to iterate through all results, check if there are more pages left and start another request until we fetched everything.

There are two functions we need to focus on. ldap_control_paged_result and ldap_control_paged_result_response

The first function enables the pagination for the current connection. The second function retrieves the information if more paged data is available (more than 1000 results). After we put everything together, we have something like that:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Example LDAP Pagination - http://www.marco-difeo.de

// We need to declare this at the outside of our do while loop!
$oPaginationCookie = "";
$oEntries = array();

// Loop for Pagination
do {
    // Set Pagination Cookie for LDAP Request
    ldap_control_paged_result($dn, 1000, true, $oPaginationCookie);

    // Search LDAP
    $ldapResult = @ldap_search($dn, $base, $searchstring, $properties, null, 1000);

    // Retrieve Paged Results
    $oLdapEntries = ldap_get_entries($this->oLDAPConnection, $ldapResult);

    // Retrieve Pagination Status (more results available?)
    // This function sets a value for $oPaginationCookie. We don't have to assign something!
    ldap_control_paged_result_response($this->oLDAPConnection, $ldapResult, $oPaginationCookie);

    // Example Code
    $oEntries = array_merge($oEntries,$oLdapEntries);

//Check if Paginationcookie has been emptied by ldap_control_paged_result_response. If yes, we have all results
}while( $oPaginationCookie !== null && $oPaginationCookie != "" );

// Do something else
Licensed under CC BY-NC-SA 4.0
Zuletzt aktualisiert am Aug 01, 2015 14:50 UTC
comments powered by Disqus
Developer / Inventor / Creator
Erstellt mit Hugo
Theme Stack gestaltet von Jimmy