php - 如何使用 PHP 从 LDAP 目录中获取用户列表?

标签 php ldap

$ldaphost = "my_host_name";
$ds=ldap_connect($ldaphost) or die("Could not connect to $ldaphost"); 
ldap_set_option ($ds, LDAP_OPT_REFERRALS, 0);
ldap_set_option ($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

if ($ds) 
{ 
    $basedn = 'my_dc_string';
    $samaccountname = 'my_user_name';
    $filters = "(samaccountname={$samaccountname})";
    $result = ldap_search($ds, $basedn, $filters);
}

如何使用 PHP 从 LDAP 获取所有用户的列表?上面的代码在 ldap_search 函数上失败并发出警告

“警告:ldap_search():搜索:操作错误”

我的用户名、ldaphost 等都是正确的。不过我不确定过滤器。

最佳答案

/**
 * Get a list of users from Active Directory.
 */
$ldap_password = 'PASSWORD';
$ldap_username = 'USERNAME@DOMAIN';
$ldap_connection = ldap_connect(HOSTNAME);
if (FALSE === $ldap_connection){
    // Uh-oh, something is wrong...
}

// We have to set this option for the version of Active Directory we are using.
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die('Unable to set LDAP protocol version');
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0); // We need this for doing an LDAP search.

if (TRUE === ldap_bind($ldap_connection, $ldap_username, $ldap_password)){
    $ldap_base_dn = 'DC=XXXX,DC=XXXX';
    $search_filter = '(&(objectCategory=person)(samaccountname=*))';
    $attributes = array();
    $attributes[] = 'givenname';
    $attributes[] = 'mail';
    $attributes[] = 'samaccountname';
    $attributes[] = 'sn';
    $result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter, $attributes);
    if (FALSE !== $result){
        $entries = ldap_get_entries($ldap_connection, $result);
        for ($x=0; $x<$entries['count']; $x++){
            if (!empty($entries[$x]['givenname'][0]) &&
                 !empty($entries[$x]['mail'][0]) &&
                 !empty($entries[$x]['samaccountname'][0]) &&
                 !empty($entries[$x]['sn'][0]) &&
                 'Shop' !== $entries[$x]['sn'][0] &&
                 'Account' !== $entries[$x]['sn'][0]){
                $ad_users[strtoupper(trim($entries[$x]['samaccountname'][0]))] = array('email' => strtolower(trim($entries[$x]['mail'][0])),'first_name' => trim($entries[$x]['givenname'][0]),'last_name' => trim($entries[$x]['sn'][0]));
            }
        }
    }
    ldap_unbind($ldap_connection); // Clean up after ourselves.
}

$message .= "Retrieved ". count($ad_users) ." Active Directory users\n";

关于php - 如何使用 PHP 从 LDAP 目录中获取用户列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13404337/

相关文章:

php - 当我刷新我的页面时,它会自动将值输入到数据库 Codeigniter

perl - 从 1000 增加限制?

svn - 如何限制对特定用户的Apache/SVN访问(基于LDAP/文件的身份验证)?

php - 标记数组排序问题

javascript - 此付款表格由于某种原因未提交

c - Go cgo ldap_init 无法确定 C.ldap_init 的名称类型

从 openLDAP 客户端到 IBM LDAP 的 ssl 连接

ldap - 如何使用 Go 与 LDAP 协议(protocol)

php - 查询用户组隐藏搜索结果

php - $val 字段需要双引号