最近做一个项目时,遇到需要通过php访问AD服务器,涉及到部分用户需要通过Ad服务器认证,并需要把ad服务器上的用户导入自己开发的系统中。
php访问AD服务器可以采用Php本身自带的Ldap协议实现库。
1、通过AD服务器认证用户
<?php
$host = "iP:端口号";
$user = "用户名@域名";
$pswd = "密码";
$ad = ldap_connect($host) or die( "Could not connect!" );
if($ad){
//设置参数
ldap_set_option ( $conn, LDAP_OPT_PROTOCOL_VERSION, 3 );
ldap_set_option ( $conn, LDAP_OPT_REFERRALS, 0 ); // Binding to ldap server
$bd = ldap_bind($ad, $user, $pswd) or die ("Could not bind");
echo "ldap_bind success";
}
else{
echo "Unable to connect to AD server"
}
?>
2、导出AD服务器上的用户
<?php
$host = "iP:端口号";
$user = "用户名@域名";//如:WEW@ttt.com
$pswd = "密码";
$ad = ldap_connect($host) or die( "Could not connect!" );
if($ad){
//设置参数
ldap_set_option ( $conn, LDAP_OPT_PROTOCOL_VERSION, 3 );
ldap_set_option ( $conn, LDAP_OPT_REFERRALS, 0 ); // Binding to ldap server
$bd = ldap_bind($ad, $user, $pswd) or die ("Could not bind");
echo "ldap_bind success";
// 指定需要获取的用户属性
$attrs = array("displayname","mail","telephonenumber","department","initials");
// 指定需查询的用户范围
$filter = "(givenname=*)";
$search = ldap_search($ad, 'dc=ttt,dc=com', $filter, $attrs)
or die ("ldap search failed");
$entries = ldap_get_entries($ad, $search);
if ($entries["count"] > 0) {
for ($i=0; $i<$entries["count"]; $i++) {
//所要获取的字段,都必须小写
echo "<p>initials: ".$entries[$i]["initials"][0]."<br />";//用户名
echo "Name: ".$entries[$i]["displayname"][0]."<br />";//用户名字
echo "Phone: ".$entries[$i]["telephonenumber"][0]."<br />";//电话号码
echo "Email: ".$entries[$i]["mail"][0]."<br />";//电子邮件
echo "department: ".$entries[$i]["department"][0]."</p>";//所在部门
}
} else {
echo "<p>No results found!</p>";
}
}
else{
echo "Unable to connect to AD server"
}
ldap_close($ad);
?>
转载请注明出处,并告知。东子哥