欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP 读取 AD 用户

程序员文章站 2022-05-23 11:27:22
...
<?php
//phpinfo();
$host = "******:389";
$user = "**@**";
$pswd = "*****";
$ad = ldap_connect($host) or die( "Could not connect!" );
if($ad){
 
//设置参数
  ldap_set_option ( $ad, LDAP_OPT_PROTOCOL_VERSION, 3 );
  ldap_set_option ( $ad, LDAP_OPT_REFERRALS, 0 ); 
  
  // bool ldap_bind ( resource $link_identifier [, string $bind_rdn = NULL [, string $bind_password = NULL ]] )
  $bd = ldap_bind($ad, $user, $pswd)  or die ("Could not bind");
  echo "ldap_bind success";
  
 //指定需要获取的用户属性
 $attrs = array("displayname","cn");
 
 //指定需查询的用户范围
 $filter   = "(objectclass=*)";
 
 //ldap_search ( resource $link_identifier , string $base_dn , string $filter [, array $attributes [, int $attrsonly [, int $sizelimit [, int $timelimit [, int $deref ]]]]] )
 $search = ldap_search($ad, 'DC=**,DC=**,DC=**', $filter, $attrs,0,0,0) or die ("ldap search failed");
 
 $entries = ldap_get_entries($ad, $search);
 
 if ($entries["count"] > 0) { 
 echo '返回记录数:'.$entries["count"];
  for ($i=0; $i<$entries["count"]; $i++) {
     //所要获取的字段,都必须小写
     if(isset($entries[$i]["displayname"])){
      echo "<p>displayname: ".$entries[$i]["displayname"][0]."<br />";//用户名
      if(isset($entries[$i]["cn"][0])){
      echo "cn: ".$entries[$i]["cn"][0]."<br />";//用户名字
      }
     }
  }
 } else {
    echo "<p>No results found!</p>";
 }
}else{
  echo "Unable to connect to AD server";
}
?>