PHP.mk документација

ldap_get_entries

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.ldap-get-entries.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.ldap-get-entries.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
ldap_get_entries

Референца за `function.ldap-get-entries.php` со подобрена типографија и навигација.

function.ldap-get-entries.php

ldap_get_entries

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_get_entries(PHP 4, PHP 5, PHP 7, PHP 8)

= NULL

ldap_get_entries(LDAP\Connection $ldap, LDAP\Result $result): array|false

Земи ги сите резултати

Параметри

ldap

Еден LDAP\Connection инстанца, вратена од ldap_connect().

result

Еден LDAP\Result инстанца, вратена од ldap_list() or ldap_search().

Вратени вредности

Чита повеќе записи од дадениот резултат, а потоа ги чита атрибутите и повеќе вредности. false при неуспех.

Враќа целосни информации за резултатот во повеќедимензионален низа на успех, или

return_value["count"] = number of entries in the result
return_value[0] : refers to the details of first entry

return_value[i]["dn"] =  DN of the ith entry in the result

return_value[i]["count"] = number of attributes in ith entry
return_value[i][j] = NAME of the jth attribute in the ith entry in the result

return_value[i]["attribute"]["count"] = number of values for
                                        attribute in ith entry
return_value[i]["attribute"][j] = jth value of attribute in ith entry

Дневник на промени

Верзија = NULL
8.1.0 На ldap параметарот очекува LDAP\Connection инстанца сега; претходно, валидна ldap link resource се очекуваше.
8.1.0 На result параметарот очекува LDAP\Result инстанца сега; претходно, валидна ldap result resource се очекуваше.

Види Исто така

  • ldap_first_entry() Структурата на низата е како што следува. Индексот на атрибутот се претвора во мали букви. (Атрибутите не се осетливи на големи и мали букви за директориум сервери, но не и кога се користат како индекси на низа.)
  • ldap_next_entry() - Врати го првиот резултат id

Белешки од корисници Пример #3 Ефект на редоследот кога се совпаѓаат повеќе кодови

chl
пред 17 години
Recursive form of markus' function so it can take directly the result of ldap_get_entries :
<?php
function cleanUpEntry( $entry ) {
  $retEntry = array();
  for ( $i = 0; $i < $entry['count']; $i++ ) {
    if (is_array($entry[$i])) {
      $subtree = $entry[$i];
      //This condition should be superfluous so just take the recursive call
      //adapted to your situation in order to increase perf.
      if ( ! empty($subtree['dn']) and ! isset($retEntry[$subtree['dn']])) {
        $retEntry[$subtree['dn']] = cleanUpEntry($subtree);
      }
      else {
        $retEntry[] = cleanUpEntry($subtree);
      }
    }
    else {
      $attribute = $entry[$i];
      if ( $entry[$attribute]['count'] == 1 ) {
        $retEntry[$attribute] = $entry[$attribute][0];
      } else {
        for ( $j = 0; $j < $entry[$attribute]['count']; $j++ ) {
          $retEntry[$attribute][] = $entry[$attribute][$j];
        }
      }
    }
  }
  return $retEntry;
}
?>

Result is of the form :
array(256) {
  ["uid=doe,ou=People,dc=example,dc=net"]=>
  array(3) {
    ["uid"]=>
    string(4) "doe"
    ["cn"]=>
    string(14) "John Doe"
    ["telephonenumber"]=>
    string(4) "1234"
  }
  ["uid=foo,ou=People,dc=example,dc=net"]=>
  ...
- Земи го следниот резултат
пред 22 години
If you're dealing with Active Directory and need to get values like 'lastlogon', 'pwdlastset' or similar, you'll notice that AD gives the values as Windows FILETIME timestamps. That means, the values are 100-nanosecond units passed since 1.1.1600 00:00:00. 

 To convert these to unix timestamps which PHP's date functions understand, one easy way would be the following : 

function win_filetime_to_timestamp ($filetime) {

  $win_secs = substr($filetime,0,strlen($filetime)-7); // divide by 10 000 000 to get seconds
  $unix_timestamp = ($win_secs - 11644473600); // 1.1.1600 -> 1.1.1970 difference in seconds
  return $unix_timestamp;
}
reaper at sci dot fi
пред 22 години
I find the ["count"] items in these arrays highly annoying, so I made a function to remove them recursively:

function rCountRemover($arr) {
  foreach($arr as $key=>$val) {
    # (int)0 == "count", so we need to use ===
    if($key === "count") 
      unset($arr[$key]);
    elseif(is_array($val))
      $arr[$key] = rCountRemover($arr[$key]);
  }
  return $arr;
}
tomas dot hampl на gmail dot com
пред 14 години
It has been mentioned in the comments below, but the <?php ldap_get_entries($connection,$result) ?> always makes all attributes into lower-case. I found out the hard way that if I'm running an ldap query against the corporate AD and then want to display some results, nothing is actually displayed unless the attribute names area in lower-case. 

Example:

<?php
// connect to AD
include('ad_con.php');
// limit attributes we want to look for
$attributes_ad = array("displayName","description","cn","givenName","sn","mail","co","mobile","company","displayName");
// define base
$base ="";

// in my script I search based on e-mail, $email variable is passed from the form
$result = ldap_search($conn, $base, "mail=$email*", $attributes_ad) or die ("Error in search
        query");

// put search results into the array ($conn variable is defined in the included 'ad_con.php')
$info = ldap_get_entries($conn, $result);

//Now, to display the results we want:
 for ($i=0; $i<$info["count"]; $i++)
    {
    // to show the attribute displayName (note the case!)
    echo $info[$i]["displayname"][0]
    
    }

?>
mackstann / mack%at%incise%dot%org
пред 4 години
To remove the annoying first entry (count) just use array_shift().
peter точка mlich на volny точка cz
пред 5 години
public function entriesToArray($entries=array())
    {
    $list  = array();
    for($i=0;$i<$entries['count'];$i++)
        {
        $row = array();
        $dn  = $entries[$i]['dn'];
        unset($entries[$i]['count']);
        unset($entries[$i]['dn']);
        foreach($entries[$i] as $key=>$value)
            {
            if (is_int($key))
                {continue;}
            $list_in_col = array();
            foreach($value as $key2=>$value2)
                {
                if (!is_int($key2))
                    {continue;}
                $list_in_col[] = $value2;
                }
            $row[$key] = $list_in_col;
            }
        $row['dn'] = $dn;
        $list[$i] = $row;
        }
    return $list;
    }

/*
Format ldap entries to better array

array (size=2)
  'count' => int 1
  0 => 
    array (size=14)
      'ou' => 
        array (size=2)
          'count' => int 1
          0 => string '03024' (length=5)
      0 => string 'ou' (length=2)
      'mail' => 
        array (size=2)
          'count' => int 1
          0 => string '[email protected]' (length=22)
      1 => string 'mail' (length=4)
      'telephonenumber' => 
        array (size=2)
          'count' => int 1
          0 => string '+420123456781' (length=13)
      2 => string 'telephonenumber' (length=15)
      'personaltitle' => 
        array (size=2)
          'count' => int 1
          0 => string 'Ing.|' (length=4)
      3 => string 'personaltitle' (length=13)
      'sn' => 
        array (size=2)
          'count' => int 1
          0 => string 'MySurname' (length=6)
      4 => string 'sn' (length=2)
      'givenname' => 
        array (size=2)
          'count' => int 1
          0 => string 'MyName' (length=5)
      5 => string 'givenname' (length=9)
      'count' => int 6
      'dn' => string 'cn=mynickid,ou=users,o=mydepartmentid' (length=24)

array (size=1)
  0 => 
    array (size=7)
      'ou' => 
        array (size=1)
          0 => string '03024' (length=5)
      'mail' => 
        array (size=1)
          0 => string '[email protected]' (length=22)
      'telephonenumber' => 
        array (size=1)
          0 => string '+420123456781' (length=13)
      'personaltitle' => 
        array (size=1)
          0 => string 'Ing.|' (length=4)
      'sn' => 
        array (size=1)
          0 => string 'MySurname' (length=6)
      'givenname' => 
        array (size=1)
          0 => string 'MyName' (length=5)
      'dn' => string 'cn=mynickid,ou=users,o=mydepartmentid' (length=24)
*/
Мауро
yasuo_ohgaki at hotmail dot com
Just a note: an multidemnsional array is like an array with in an array.... you have myArray[2]-> can refer to something like dc=americas,dc=icm,dc=org

Basically you have more elements that are buried with in one element of the parent array[], myArray[2]

So, thats why you see myArray[1]["dn"][0] ... pulling out the first element in myArray[1] and rollover the first element in it.
john at petbrain dot com
20 години пред
When you like to get the entry from LDAP in the same style as ldap_add(), then you can use the following function to convert this entry.

<?php
/**
 * Take an LDAP and make an associative array from it.
 * 
 * This function takes an LDAP entry in the ldap_get_entries() style and
 * converts it to an associative array like ldap_add() needs.
 * 
 * @param array $entry is the entry that should be converted.
 * 
 * @return array is the converted entry.
 */
function cleanUpEntry( $entry ) {
    $retEntry = array();
    for ( $i = 0; $i < $entry['count']; $i++ ) {
        $attribute = $entry[$i];
        if ( $entry[$attribute]['count'] == 1 ) {
            $retEntry[$attribute] = $entry[$attribute][0];
        } else {
            for ( $j = 0; $j < $entry[$attribute]['count']; $j++ ) {
                $retEntry[$attribute][] = $entry[$attribute][$j];
            }
        }
    }
    return $retEntry;
}
?>
markus dot schabel at tgm dot ac dot at
20 години пред
Helmuts programming example is incorrect.

PHP arrays start from zero, so your first entry is $entry[0] and your last entry is $entry[$entry["count"] - 1].

$entry[$entry["count"]] will never exist, thus his usage of is_null.

Helmuts usage of is_null is not elegant, its just poor understanding of arrays.

Save some confusion and remove Helmuts entry and this one.
reuben dot helms at gmail dot com
20 години пред
Another way of ignoring the last null entry would be to subtract one from the iteration count like this:

for($i = 0; $i < count($result_array) - 1; $i++)
{
     ...
}

Helmut's method is far more elegant on its own but what I do is combine the above with the null test that he suggested. It may seem like overkill, but better safe than sorry.
Jim Granger <tenor at jimgranger.com>
figroc at gmail dot com
In response to the first message ldap_get_entries, I think there is some confusion with the dynamic typing of php.

If the result is a string doing $foo[0] will return the first character of the string. 

In the case of an array $foo[0] will return the entire first element.

Its not to do with the 'dn' in particular, rather the fact that the dn is a scalar value (ie a string) rather than an array, and the indexing works differently in either case.

For debugging purposes I would recommend using something like :

$value = is_array($foo) ? $foo[0] : $foo;

or 

$value = is_array($foo) ? implode($foo, $delimiter) : $foo;
c dot green at its dot uq dot edu dot au
пред 22 години
I have found that ldap_get_entries() function doesn't handle binary data correctly.  I had to write my own using ldap_get_values_len(). 

// will use ldap_get_values_len() instead and build the array
// note: it's similar with the array returned by
// ldap_get_entries() except it has no "count" elements
$i=0;
$entry = ldap_first_entry($this->conn, $this->srchRslt);
do {
     $attributes = ldap_get_attributes($this->conn, $entry);
     for($j=0; $j<$attributes['count']; $j++) {
        $values = ldap_get_values_len($this->conn, $entry,$attributes[$j]);
        $this->rawData[$i][$attributes[$j]] = $values; 
     }          
     $i++;                
    } 
while ($entry = ldap_next_entry($this->conn, $entry));
//we're done
return ($this->rawData);
Ovidiu Geaboc <ogeaboc at rdanet.com>
figroc at gmail dot com
Actually, the fact that ldap_get_entries returns attribute names as lowercase is really annoying, because ldap_get_attributes apparently does not.  This is really annoying, especially when having arrays of attribute names and having to worry about which call was used to retrieve entries from LDAP.
pmichaud at pobox dot com
yasuo_ohgaki at hotmail dot com
Note that ldap_get_entries return an associative array with the attributes in lower case.  So for example the givenName ldap attribute is associated with $ldap[0]["givenname"][0] (for the first given name for the first result) this is a little confusing at first.
cbrent at orix dot com dot au
figroc at gmail dot com
Note: ldap_get_entries returns true even if no results are found, like this:

echo $entries=ldap_get_entries(...);

will print Array.

You have to check for number of row in the Array like this:

if($entries["count"]==0) return false;

Hope this helped someone...
oscara at hinux dot hin dot no
пред 18 години
Some code I put together. Maybe yall can benefit from it.

<?php
function search_results($info) {
  foreach ($info as $inf) {
    if (is_array($inf)) {
      foreach ($inf as $key => $in) {
        if ((count($inf[$key]) - 1) > 0) {
          if (is_array($in)) {
            unset($inf[$key]["count"]);
          }
          $results[$key] = $inf[$key];
        }
      }
    }
  }
  $results["dn"] = explode(',', $info[0]["dn"]);
  return $results;
}

$user = "asohn";

$ds = ldap_connect("ldap://DOMAIN.net");
if ($ds) {
  $r = ldap_bind($ds);
  $sr = ldap_search($ds, "ou=customers,dc=DOMAIN,dc=net", "uid=".$user);
  $info = ldap_get_entries($ds, $sr);
  
  echo $info["count"]." Search Result(s) for \"".$user."\"\n";
  
  $results = search_results($info);
  foreach ($results as $key => $result) {
    echo "  ".$key."\n";
    if (is_array($result)){
      foreach($result as $res){
        echo "    ".$res."\n";
      }
    }
  }
  ldap_close($ds);
}
?>
Себастиен Тројани
пред 16 години
Looks like there is a limit on returned objects - only 1000 items are placed in the array
хелмут дот патај ат скандио дот де
21 години пред
If you loop over the entries, like
$entries = ldap_get_entries( $ds, $sr );
watch out!
you have to check with is_null the last entry
because you will get one entry more than the search found,
but the last one will be null
so you are safe if you do:
for ( $i = 0; $i < count( $entries ); $i++ ) {
    if ( is_null( $entries[ $i ] ) ) continue;
    ...
}
плонки ат џимејл дот ком
пред 16 години
Hope this could help a bit others to print attribute and values on the same line. This is basic code of course 

<?php

$ldap_con = ldap_connect($ldap_server) or die("Could not connect to server. Error is " . ldap_error($ldap_con));
$ldap_bd = ldap_bind($ldap_con, $root_dn, $root_pw) or die("Could not bind to server. Error is " .ldap_error($ldap_con));
$result = ldap_search($ldap_con, $personnel_base, "(uid=*)") or die ("Error in query");

$data = ldap_get_entries($ldap_con, $result);

for ($i=0; $i<=$data["count"];$i++) {
        for ($j=0;$j<=$data[$i]["count"];$j++){
        echo $data[$i][$j].": ".$data[$i][$data[$i][$j]][0]."\n";
        }
}
ldap_close($ldap_con);
?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.