如何在PHP8中获得分页LDAP查询并读取1000多个条目



我需要获取当前LDAP搜索返回的1000多个条目。目前,我在一台装有IIS和PHP 7.4的Windows服务器上运行,但很快就会升级到8.0。

到目前为止,我尝试过的是:

# Connect to the LDAP server
$ldap = ldap_connect("ldaps://my.ldap.server:636");
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
$ldapBind = ldap_bind($ldap, "UserName", "Password");
# Do a search
$searchResult = ldap_search($ldap, "DC=something1,DC=something2", "LDAP query);
$countEntries += ldap_count_entries($ldap, $searchResult);
$info = ldap_get_entries($ldap, $searchResult);
# Process each found LDAP data row - this will be a maximum of 1000 rows
for($i=0; $i < $info["count"]; $i++) {
# do something ...
}

这只会给我前1000行,但我需要阅读至少30000行。使用";命名查询";像mail=a*mail=b*这样的解决方案是不可行的,因为其中可能有1000多个条目,所以我需要某种可信的分页方法——一页接一页。

我可以看到,我很可能应该使用LDAP控件,因为ldap_control_paged_result在PHP 7.4之后不再是一个选项,但我真的不明白——如何使用它?

有人能给我一些提示吗?:-(

PHP文档中有一个关于如何在PHP 7.4+中从LDAP获取数据并对其进行分页的示例(参见示例#5(。

官方文档中的以下代码片段已调整为每页750项的页面大小。

// $link is an LDAP connection
$cookie = '';
do {
$result = ldap_search(
$link, 'dc=example,dc=base', '(cn=*)', ['cn'], 0, 0, 0, LDAP_DEREF_NEVER,
[['oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => ['size' => 750, 'cookie' => $cookie]]]
);
ldap_parse_result($link, $result, $errcode , $matcheddn , $errmsg , $referrals, $controls);
// To keep the example short errors are not tested
$entries = ldap_get_entries($link, $result);
foreach ($entries as $entry) {
echo "cn: ".$entry['cn'][0]."n";
}
if (isset($controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'])) {
// You need to pass the cookie from the last call to the next one
$cookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'];
} else {
$cookie = '';
}
// Empty cookie means last page
} while (!empty($cookie));

最新更新