控制 PHP ldap 分页 - 结果数和页码

Controlling PHP ldap pagination - number of results and page number

您好,这已经发生了一些,但希望我能对这个问题有所了解。基本上我想使用 ldap 在我的活动目录中进行搜索并对结果进行分页。

我见过这样的代码,但对我来说没有任何意义

// $ds is a valid link identifier (see ldap_connect)
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$dn        = 'ou=example,dc=org';
$filter    = '(|(sn=Doe*)(givenname=John*))';
$justthese = array('ou', 'sn', 'givenname', 'mail');

// enable pagination with a page size of 100.
$pageSize = 100;

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

  $result  = ldap_search($ds, $dn, $filter, $justthese);
  $entries = ldap_get_entries($ds, $result);

  foreach ($entries as $e) {
    echo $e['dn'] . PHP_EOL;
  }

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

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

这实际上是做什么的? cookie 是什么意思?

我可以代替

$result  = ldap_search($ds, $dn, $filter, $justthese); 

$result  = ldap_search($ds, $dn, $filter, $justthese,0,100);

这将使用过滤器并获取前 100 行。

手头的问题是如何成功控制ldap分页。即将结果的数量提供给 return 和我想要的页面。


更新

对上面的代码,我给了它一个 运行 它所做的是 运行 搜索,多次 - return 在每次迭代中创建一个新页面直到结束。所以 cookie 似乎对此有一些控制。

对,我想答案是这样的。

a) $cookie 参数是与搜索和分页相关的内部操作,您不能 edit/control 这个(或者至少我找不到方法)。

b) 使用上述代码的原因是如果您的服务器对 ldap 可以访问的用户数量有一些限制 return.

c) 如果您确实使用上面的代码进行搜索,则不能使用 ldap_sort 因为这只会对每个页面进行排序。

d) 所以这会引导您创建一个数组,然后使用 php 函数,例如 asort 对数组进行排序,然后让您的页面使用 array_splice

所以 ldap 分页的解决方案是使用这样的代码

$filter = "(&(displayName=*".ldap_escape('r')."*)(samaccountname=*)(givenname=*)(sn=*)(lastlogontimestamp=*))";


$justthese = array('ou', 'sn', 'givenname', 'mail');

$sr  = ldap_search($conn['connect'], $conn['base_dn'], $filter, $justthese);
ldap_sort ( $conn['connect'], $sr, 'givenname' ) ; 
$info = ldap_get_entries($conn['connect'], $sr);

$offset = $page_number*$number;
$length = $number;


unset($info['count']);

$info = array_slice ($info, $offset ,$length);


echo '<pre>';
print_r($info);
echo '</pre>';

还有一件事 ldap_sort 看起来有点垃圾,因为它区分大小写。我想你可以在得到结果后自己写,如果这不是你的菜。 更新 - 如果有很多结果,这是行不通的,而且按照您可能最好使用 array_reverse

之类的顺序

所以你去吧,不是很好但可行。尝试改进此问题的其他解决方案是当搜索发生查询 ldap 时,将结果存储在 sql table 中。让用户使用 sql table 操纵结果 (sort/pagination)。每次搜索都会获得 table 的一组新结果。然后你得到 sql table 的速度和它的好处 sorting/pagination,但插入会花费你。

所以没有很好的解决方案,只有一些可行的想法。 希望对大家有帮助。

Cookie 包含指向结果集当前 returned 部分的内部指针(资源)。因此,为了让服务器知道从哪里继续,您必须将指针作为参数返回。至少目前是这样,但有改变这种情况的想法。我将不得不进行一些挖掘以找到它的当前状态。

您将 returned 项目的数量设置为 100 的第二个想法将 return 一遍又一遍地得到相同的结果,因为它设置了服务器将 return 对于每个请求。

但是你必须小心排序!目前只有 ldap_sort(自 PHP 7 起已弃用)在客户端对结果集进行排序。但是由于分页是在服务器端完成的,目前还没有办法进行服务器端排序(我们正在努力),结果将不是您所期望的。