PDA

Просмотр полной версии : вывод информации из ldap


Masha_25
29.07.2009, 17:32
Здравствуйте.
У меня такая проблема,мне нужно вывести информацию 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:

Pashkela
29.07.2009, 19:42
хз, у меня всё компилируется без ошибок, скобки расставь просто правильно, глаза сломаешь:

<?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++;
}
}
}
?>


Никаких синтаксических ошибок нет, возможно была тут:

$results = ldap_read($ldapconn, $srdn, '(objectclass=person)',
array("givenName", "sn", "mail"));

но в пример выше я склеил, всё комплится

BlackSun
30.07.2009, 00:47
ActiveDirectory.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->ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
}
// 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
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>';
}
?>