我需要帮助用PHP查询LDAP

时间:2014-02-14 19:46:57

标签: php ldap

********请完整阅读问题......我正在试图弄清楚如何让LDAP查询工作......我不是在问为什么我得到一个未定义的变量错误,我只是说这是我在运行代码时遇到的唯一错误。我知道需要定义变量,即使定义了变量,也不会返回任何结果。

我正在尝试使用php搜索LDAP。我不需要添加或编辑信息,只需提取搜索结果即可。我一直在阅读php手册条目和我可以使用的示例,但我仍然遇到一些麻烦。使用下面的代码,我得到的唯一错误是

  

“注意:未定义的变量:ldapSearch()中的ad_users(第42行)   C:\ Program Files   (86)\ Zend的\的Apache2 \ htdocs中\ TLSConnect3App \网站\所有\模块\定制\ TLSConnectPackage \ ldap_search \包括\的functions.php)“。

我也试图找出在LDAP中找到samaccountname的位置。那是uid还是displayName?我的最终目标是能够搜索姓名或电子邮件,并提取用户照片,姓名,名单,电子邮件和电子邮件。

<?php
function ldapSearch(){
    $ldap_password = 'H******5!!1';
    $ldap_username = 'cn=Directory Manager';
    $ldaphost = "ldap-server";
    $ldapport = 389;

    $ldapconn = ldap_connect($ldaphost,$ldapport)
        or die('Could not connect to '.$ldaphost);

    // We have to set this option for the version of Active Directory we are using.
    ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3) or die('Unable to set LDAP protocol version');
    ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0); // We need this for doing an LDAP search.

    if (TRUE === ldap_bind($ldapconn, $ldap_username, $ldap_password)){
        $ldap_base_dn = 'DC=,DC=co,DC=uk';
        $search_filter = '(&(objectCategory=person)(displayName= Admin))';
        $attributes = array();
        $attributes[] = 'givenName';
        $attributes[] = 'mail';
        $attributes[] = 'samaccountname';
        $attributes[] = 'sn';
        $result = ldap_search($ldapconn, $ldap_base_dn, $search_filter, $attributes);
        $entries = ldap_get_entries($ldapconn, $result);
        if (FALSE !== $result){
            $entries = ldap_get_entries($ldapconn, $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]) &&
                    'Shop' !== $entries[$x]['sn'][0] &&
                    'Account' !== $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($ldapconn); // Clean up after ourselves.
    }

$message = "Retrieved ". count($ad_users) ." Active Directory users\n";
}

2 个答案:

答案 0 :(得分:0)

尝试在函数开头定义$ad_users = array()

答案 1 :(得分:0)

问题是$ad_usersif块内定义,然后在其外部使用。如果跳过if块,则不会定义变量,您将收到通知。

$something = false;

if ($something == true) { // This will be skipped
    $myVar = 'It works!'; // And this variable will not be defined
}
echo $myVar; // Notice: Undefined variable: myVar

简而言之,如果要使用它,则需要确保$ad_users已定义。最简单的方法是简单地在函数顶部定义变量;这样它将始终在整个功能中可用。

相关问题