PHP

php中ldap怎么查询用户和组

小亿
208
2024-05-21 17:37:28
栏目: 编程语言

在PHP中可以使用LDAP(Lightweight Directory Access Protocol)来查询用户和组。以下是一个简单的示例代码:

  1. 连接LDAP服务器:
$ldapServer = 'ldap://ldap.example.com';
$ldapPort = 389;
$ldapConn = ldap_connect($ldapServer, $ldapPort);
  1. 绑定LDAP管理员账号:
$ldapAdmin = 'cn=admin,dc=example,dc=com';
$ldapPassword = 'password';
ldap_bind($ldapConn, $ldapAdmin, $ldapPassword);
  1. 查询用户:
$ldapBaseDn = 'ou=users,dc=example,dc=com';
$ldapFilter = '(objectClass=person)';
$ldapAttributes = array('cn', 'mail');

$ldapSearch = ldap_search($ldapConn, $ldapBaseDn, $ldapFilter, $ldapAttributes);
$ldapEntries = ldap_get_entries($ldapConn, $ldapSearch);

foreach ($ldapEntries as $entry) {
    echo "Username: " . $entry['cn'][0] . ", Email: " . $entry['mail'][0] . "<br>";
}
  1. 查询组:
$ldapGroupBaseDn = 'ou=groups,dc=example,dc=com';
$ldapGroupFilter = '(objectClass=groupOfUniqueNames)';
$ldapGroupAttributes = array('cn', 'uniqueMember');

$ldapGroupSearch = ldap_search($ldapConn, $ldapGroupBaseDn, $ldapGroupFilter, $ldapGroupAttributes);
$ldapGroupEntries = ldap_get_entries($ldapConn, $ldapGroupSearch);

foreach ($ldapGroupEntries as $entry) {
    echo "Group: " . $entry['cn'][0] . "<br>";
    foreach ($entry['uniquemember'] as $member) {
        echo "Member: " . $member . "<br>";
    }
}

请注意,以上代码仅供参考,具体的LDAP服务器配置和数据结构可能会有所不同。在实际应用中,您需要根据您的LDAP服务器的配置和数据结构进行相应的调整。

0
看了该问题的人还看了