php连接LDAP服务器(Active Directory)及信息的检索
LDAP是个Protocol,目前常用的实现有如下三种方案:
1 NDS(Novell Directory Services)
2 Microsoft Active Directory
3 OpenLDAP
要实现LDAP,第一步是设计DIT(即Directory Information Tree)。
以下连接代码在Microsoft Active Directory(即AD)下验证通过。
最简单的bind方式:
<?php
// LDAP variables
$ldaphost = "192.168.8.5"; // your ldap servers
$ldapport = 389; // your ldap server's port number
// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost, $ldapport) or die("Could not connect to $ldaphost");
$ldaprdn = "testuser"; // ldap rdn or dn
$ldappass = 'testpwd'; // associated password
if ($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
//var_dump($ldapbind);
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...";
} else {
echo "LDAP bind failed...";
}
}
// LDAP variables
$ldaphost = "192.168.8.5"; // your ldap servers
$ldapport = 389; // your ldap server's port number
// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost, $ldapport) or die("Could not connect to $ldaphost");
$ldaprdn = "testuser"; // ldap rdn or dn
$ldappass = 'testpwd'; // associated password
if ($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
//var_dump($ldapbind);
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...";
} else {
echo "LDAP bind failed...";
}
}
是否能采用这种方式,取决于Directory Information Tree的结构。该方式存在明显缺点,要么bind成功,要么失败。即无法分别是用户名错误,还是密码错误。
search方式:
$ldap_host = "192.168.8.5";
$ldap_port = "389";
$base_dn = "OU=zzz,DC=test,DC=com,DC=cn";
$filter = "(cn=*)";
$ldap_user ="cn=admin,OU=zzz,DC=test,DC=com,DC=cn";
$ldap_pass = "123456";
$connect = ldap_connect( $ldap_host, $ldap_port);
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
$bind = ldap_bind($connect, $ldap_user, $ldap_pass);
$read = ldap_search($connect, $base_dn, $filter);
$info = ldap_get_entries($connect, $read);
echo $info["count"]." entrees retournees<BR><BR>";
for($ligne = 0; $ligne<$info["count"]; $ligne++)
{
for($colonne = 0; $colonne<$info[$ligne]["count"]; $colonne++)
{
$data = $info[$ligne][$colonne];
echo $data.":".$info[$ligne][$data][0]."<BR>";
}
echo "<BR>";
}
ldap_close($connect);
其中:
$ldap_user ="cn=admin,OU=zzz,DC=test,DC=com,DC=cn";
$ldap_pass = "123456";
这两个语句定义了一个专用的LDAP账户用于登陆到LDAP服务器,该帐号必须具有检索权限。
在登录到LDAP服务器之后,就可以对LDAP中的信息进行检索(ldap_search)了,此时就可以判断某个id是否存在,密码是否正确等等。
在具体开发中采用哪种方式,取决于Directory Information Tree的设计。