yusof
yusof

Reputation: 163

PHP LDAP pagination

I'm building a PHP script that will get all the users under a specific person, basically direct reports which can get very big.

I managed to get the script working for 1000 entries. I found this site https://doc.bccnsoft.com/docs/php-docs-7-en/function.ldap-control-paged-result.html and fit it around my code. The problem is, I don't know how to make this script run for anything over 1000 entries. I'm wanting it to return 2000, 5000, 10,000 records until it's done getting the data asked for.

<?php
set_time_limit(60);

$executionStartTime = microtime(true);
//LDAP Directory Services Settings
define("LDAP_SERVER", "test.com");
define("LDAP_DN", "OU=Users,DC=test,DC=com");
define("USER", "test");
define("LDAP_DOMAIN", "@test.com");
define("LDAP_USER", "test");
define("LDAP_PASS", "password");

/* Connect to LDAP Server */
$ds = ldap_connect(LDAP_SERVER);

/* Bind to LDAP Server */
$user_fqdn = LDAP_USER.LDAP_DOMAIN;
$bind = @ldap_bind($ds, $user_fqdn, LDAP_PASS);
//@ldap_bind($ldapconn, $ldapuser."@test.com", $ldappass);

/* Options for searching Whole Domain */
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
//ldap_set_option($ds, LDAP_OPT_SIZELIMIT, 5);

/* Search Filter */ 
$filter = "(&(objectCategory=Person)(sAMAccountName=*)(manager:1.2.840.113556.1.4.1941:=cn=".USER.",OU=Users,DC=test,DC=com))";

$justthese = array('mail', 'employeeType', 'manager');
/* Search */
$pageSize = 1000;

 $cookie = '';
 do {
     ldap_control_paged_result($ds, $pageSize, true, $cookie);

     $result  = ldap_search($ds, LDAP_DN, $filter, $justthese);
     $entries = ldap_get_entries($ds, $result);
     echo "<pre>";
     var_dump($entries);   
    echo "</pre>";       

     ldap_control_paged_result_response($ds, $result, $cookie);

 } while($cookie !== null && $cookie != '');


$executionEndTime = microtime(true);
$seconds = $executionEndTime - $executionStartTime;

//Print it out
echo "This script took " . $seconds . " to execute.";

?>

Basically, i'm wanting this to run on a cron job and just get all the entries from ldap and dump it into a database (i've not yet gotten to the db part). Not only 1000 records.

Upvotes: 1

Views: 635

Answers (1)

EricLavault
EricLavault

Reputation: 16095

You need to set the protocol version before binding, especially with AD :

$ds = ldap_connect(LDAP_SERVER);
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$user_fqdn = LDAP_USER.LDAP_DOMAIN;
$bind = @ldap_bind($ds, $user_fqdn, LDAP_PASS);

Your code seems fine in the do/while loop.

Upvotes: 1

Related Questions