php連接LDAP服務器(Active Directory)及信息的檢索

作者: rethink  來源: 博客園  發布時間: 2010-11-08 15:22  閱讀: 2719 次  推薦: 0   原文鏈接   [收藏]  
  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...";
    }

}

  是否能采用這種方式,取決于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的設計。

0
0
 
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()