вывод информации из ldap

Discussion in 'PHP' started by Masha_25, 29 Jul 2009.

  1. Masha_25

    Masha_25 New Member

    Joined:
    29 Jul 2009
    Messages:
    1
    Likes Received:
    0
    Reputations:
    0
    Здравствуйте.
    У меня такая проблема,мне нужно вывести информацию displayName из LDAP.Вроде уже нашла похожий пример в инете,но мне пишет странную ошибку(хотя я просто скопировала код программы и на мой взгляд должно работать :mad: ):
    Parse error: syntax error, unexpected $end in /var/www/dva.php on line 35
    Причем 35 строка это последняя ковычка...
    Вот код:
    <?php
    $srdn = 'ou=Users,dc=uni-protvino,dc=ru';

    $ldapconn = ldap_connect("ldap://backup.uni-protvino.ru", 389)
    or die("Not connect: $ldaphost ");
    ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);

    if ($ldapconn)
    {

    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn);

    // verify binding
    if ($ldapbind)
    {
    $results = ldap_read($ldapconn, $srdn, '(objectclass=person)',
    array("givenName", "sn", "mail"));
    $firstname = ldap_get_values($ldapconn, $results, "givenname");
    $lastname = ldap_get_values($ldapconn, $results, "sn");
    $mail = ldap_get_values($ldapconn, $results, "mail");

    echo "First name: ".$firstname[0]."<br />";
    echo "Last name: ".$lastname[0]."<br />";
    echo "Email addresses: ";

    $x=0;
    while ($x < $mail["count"])
    {
    echo $mail[$x]. " ";
    $x++;
    }

    }
    }
    ?>


    Помогите пожалуйста :confused:
     
  2. Pashkela

    Pashkela Динозавр

    Joined:
    10 Jan 2008
    Messages:
    2,750
    Likes Received:
    1,044
    Reputations:
    339
    хз, у меня всё компилируется без ошибок, скобки расставь просто правильно, глаза сломаешь:
    PHP:
    <?php
    $srdn 
    'ou=Users,dc=uni-protvino,dc=ru';
    $ldapconn ldap_connect("ldap://backup.uni-protvino.ru"389) or die("Not connect: $ldaphost ");
    ldap_set_option($adLDAP_OPT_PROTOCOL_VERSION3);

    if (
    $ldapconn) {
        
    // binding to ldap server
        
    $ldapbind ldap_bind($ldapconn);
        
    // verify binding
        
    if ($ldapbind) {
           
    $results ldap_read($ldapconn$srdn'(objectclass=person)', array("givenName""sn""mail"));
           
    $firstname ldap_get_values($ldapconn$results"givenname");
           
    $lastname ldap_get_values($ldapconn$results"sn");
           
    $mail ldap_get_values($ldapconn$results"mail");
           echo 
    "First name: ".$firstname[0]."<br />";
           echo 
    "Last name: ".$lastname[0]."<br />";
           echo 
    "Email addresses: ";
           
    $x=0;
           while (
    $x $mail["count"]) {
              echo 
    $mail[$x]. " ";
              
    $x++;
           } 
         }
    }
    ?>
    Никаких синтаксических ошибок нет, возможно была тут:
    PHP:
    $results ldap_read($ldapconn$srdn'(objectclass=person)',
    array(
    "givenName""sn""mail"));
    но в пример выше я склеил, всё комплится
     
  3. BlackSun

    BlackSun Banned

    Joined:
    1 Apr 2007
    Messages:
    989
    Likes Received:
    1,168
    Reputations:
    446
    ActiveDirectory.php
    PHP:
    <?php
        
    /**
         * Simple class for working with LDAP
         * by BlackSun [S.T.A.R.S. Team]
         * 
         * PS: не проверял, может где то накосячил ..
         */
        
    class ActiveDirectory
        
    {
            protected 
    $ldap;
            protected 
    $bind;
            protected 
    $base_dn;
            protected 
    $ldap_username;
            protected 
    $ldap_password;
            public 
    $use_ssl;
            public 
    $use_protocol_v3;
            public 
    $ldap_host;
            public 
    $ldap_port;
            
            
    /**
             * Инициализация
             *
             * @param string $host
             * // важно правильно задать этот параметр, иначе нифига пахать не будет
             * @param string $base_dn
             * @param string $username
             * @param string $password
             * @param int $port default = 389
             * @param BOOL $use_ssl default = False
             * @param BOOL $protocol_v3 default = True
             */
            
    public function __construct($host$base_dn$username$password$port 389$use_ssl False$protocol_v3 True)
            {
                
    /**
                 * инициализируем переменные
                 */
                
    define ('ADLDAP_NORMAL_ACCOUNT'805306368);
                
                
    $this->base_dn $base_dn;
                
    $this->ldap_username $username;
                
    $this->ldap_password $password;
                
    $this->ldap_host $host;
                
    $this->ldap_port $port;
                
    $this->use_ssl $use_ssl;
                
    $this->use_protocol_v3 $protocol_v3;
                
                if (
    $use_ssl)
                {
                    
    $this->ldap_host 'ldaps://' $this->ldap_host;
                }
                
                
    /**
                 * соеденяемся
                 */
                
    $this->ldap ldap_connect($this->ldap_host$this->ldap_port);
                if (!
    $this->ldap)
                {
                    die(
    'Can\'t connect to Active Directory :(<br />' 'LDAP Error: ' ldap_error($this->ldap));
                }
                
                
    /**
                 * выставляем необходимые опции
                 */
                
    if ($protocol_v3)
                {
                    
    ldap_set_option($this->ldapLDAP_OPT_PROTOCOL_VERSION3);
                }
                
    // ldap_set_option($this->_conn, LDAP_OPT_REFERRALS, 0);
                
                /**
                 * биндимся
                 */
                
    $this->bind ldap_bind($this->ldap$this->ldap_username$this->ldap_password);
                if (!
    $this->bind)
                {
                    if (
    $this->use_ssl)
                    {
                        die(
    'Error: AD bind failed. Try with no SSL.<br /> LDAP Says: ' ldap_error($this->ldap));
                    } else {
                        die(
    'Error: AD bind failed. Try to use SSL.<br /> LDAP Says: ' ldap_error($this->ldap));
                    }
                }
                
                return 
    True;
            }
            
            public function 
    __destruct()
            {
                
    ldap_close($this->ldap);
            }
            
            
    /**
             * функция выдачи списка юзверей
             *
             * @param array $fields
             * @param string $search
             * @return Array or False
             * 
             * возвращает массив:
             *         array {
             *             count => кол-во найденых юзверей
             *             result => array {
             *                     id => array {
             *                             field => value
             *                         }
             *                 }
             *         }
             * 
             * Example:
             *         // Иванов Федор Пупович
             *         echo $result['result'][0]['displayname'];
             */
            
    public function GetUsersList($fields = array('displayname'), $search '*')
            {
                
    $filter '(&(objectClass=user)(samaccounttype=' ADLDAP_NORMAL_ACCOUNT ")(objectCategory=person)(cn=$search))";
                
    $ldap_search ldap_search($this->ldap$this->base_dn$filter$fields);
                if (!
    $ldap_search)
                {
                    echo 
    'LDAP Search error. LDAP Says: ' ldap_error($this->ldap);
                    return 
    False;
                }
                
                
    $entries ldap_get_entries($this->ldap$ldap_search);
                
    $users_array = array();
                
    $count ldap_count_entries($this->ldap$ldap_search);
                
    $result = array('count' => $count'result' => array());
                if (
    $count 0)
                {
                    for (
    $i 0$i $count$i++)
                    {
                        foreach (
    $fields as $field)
                        {
                            
    $result['result'][$i][$field] = $entries[$i][$field][0];
                        }
                    }
                }
                
                return 
    $result;
            }
        }
    ?>
    index.php
    PHP:
    <?php
        
    require ('ActiveDirectory.php');
        
        
    // насчет dc в base_dn что то я сомневаюсь, может все же не uni-protvino, а uni-protvino.ru ?
        // и создайте нового юзера с правами на чтение, у меня с анонимусом были проблемы
        
    $ldap = new ActiveDirectory('backup.uni-protvino.ru''ou=Users,dc=uni-protvino,dc=ru',
                
    'adUserReadOnly''adUserPassword');
        
    $users $ldap->GetUsersList(array('displayname'), '*');
        
        if (
    $users)
        {
            echo 
    'Count: ' $users['count'] . '<br /><pre>';
            
    print_r($users);
            echo 
    '</pre>';
        }
    ?>