PHP LDAP:ldap_search上遇到错误

时间:2014-01-03 02:11:26

标签: php ldap

我在互联网上获得了这段代码并进行了一些修改。我打算通过将输入的用户ID和密码与我们的AD进行匹配来验证我的网站用户。

代码似乎有效但当我尝试添加mail属性时,我收到此错误:

Notice: Undefined index: mail in C:\xampp\htdocs\ldap\index2.php on line 34
Retrieved 1 Active Directory users 

请帮我找错。我想获取用户的邮件并将其显示在屏幕上。

<?php

$ldap_password = "mypassword";
$ldap_username = "myusername@domain";
$ldap_connection = ldap_connect("domain");
if (FALSE === $ldap_connection){
    echo "you are not connected to ldap server";
}

ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die('Unable to set LDAP protocol version');
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);

if (TRUE === ldap_bind($ldap_connection, $ldap_username, $ldap_password)){
    $ldap_base_dn = "DC=something,DC=something,DC=something";
    $search_filter = "(&(objectCategory=person)(samaccountname=myusername))";
    $attributes = array();
    $attributes[] = "givenname";
    $attributes[] = "mail";
    $attributes[] = "samaccountname";
    $attributes[] = "sn";
    $result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter, $attributes);
    if (FALSE !== $result){
        $entries = ldap_get_entries($ldap_connection, $result);
        for ($x=0; $x<$entries['count']; $x++){
            if (!empty($entries[$x]['givenname'][0]) || 
                !empty($entries[$x]['mail'][0]) || 
                !empty($entries[$x]['samaccountname'][0]) || 
                !empty($entries[$x]['sn'][0])
                ){
                $ad_users[strtoupper(trim($entries[$x]['samaccountname'][0]))] = array('email' => strtolower(trim($entries[$x]['mail'][0])),'first_name' => trim($entries[$x]['givenname'][0]),'last_name' => trim($entries[$x]['sn'][0]));
            }
        }
    }
    ldap_unbind($ldap_connection); 
}

echo "Retrieved ". count($ad_users) ." Active Directory users\n";

?>

1 个答案:

答案 0 :(得分:0)

您确定属性名为mail吗?当您使用ldapsearch之类的“已知工作工具”查询LDAP时,您会得到什么?在类似* nix的系统上,您应该能够使用以下命令查询LDAP:

ldapsearch -h domain -b DC=something,DC=something,DC=something "(&(objectCategory=person)(samaccountname=myusername))" givenname,mail,samaccountname,sn

你得到了预期的结果吗?结果是否包含mail的条目?

或者,您可以插入var_dump($entries[$x])作为for循环的第一项,以查看是否已设置mail - 属性。

希望有所帮助