You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现LDAP认证时如何在两个OU中搜索用户

PHP LDAP双OU降级检索实现方案

需求说明

现有可正常运行的PHP LDAP认证脚本,因Windows系统迁移需求,临时存在两个OU,需实现检索逻辑:优先在第一个OU检索目标用户,未命中时自动到第二个OU检索。

已有配置与代码

已定义的两个OU DN

$ldap_dn = "OU=Company,DC=mydomain,dc=de";
$ldap_dn2 = "OU=CompanyNew,DC=mydomain,dc=de";

原单OU检索逻辑

// 原德语报错LDAP-Server kann nicht durchsucht werden!已翻译为中文
$result = ldap_search($ldap, $ldap_dn, $filter, $attr) or exit("无法检索LDAP服务器!");

最终实现代码

/**
 * 双OU降级检索LDAP用户
 * @param  resource $ldap LDAP连接资源
 * @param  string $ldap_dn 第一个OU的DN
 * @param  string $ldap_dn_2 第二个OU的DN
 * @param  string $filter 检索过滤条件
 * @param  array $attr 需要返回的属性列表
 * @return resource LDAP检索结果资源
 */
function performLDAPSearch($ldap, $ldap_dn, $ldap_dn_2, $filter, array $attr)
{
    // 优先检索第一个OU
    $result = ldap_search($ldap, $ldap_dn, $filter, $attr);
    $entries = ldap_get_entries($ldap, $result);
    // 第一个OU未命中,检索第二个OU
    if (!$entries || count($entries) == 0) {
        $result = ldap_search($ldap, $ldap_dn_2, $filter, $attr);
    }
    // 检索失败抛出错误
    if (!$result) {
        exit("无法检索LDAP服务器!");
    }
    return $result;
}

调用方式

替换原单OU检索代码为如下调用即可:

$result = performLDAPSearch($ldap, $ldap_dn, $ldap_dn2, $filter, $attr);

内容的提问来源于stack exchange,提问作者djaenz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:06:05