PHP Doku:: Liefert alle Ergebnis-Einträge - function.ldap-get-entries.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzSonstige DiensteLightweight Directory Access ProtocolLDAP Funktionenldap_get_entries

Ein Service von Reinhard Neidl - Webprogrammierung.

LDAP Funktionen

<<ldap_get_dn

ldap_get_option>>

ldap_get_entries

(PHP 4, PHP 5)

ldap_get_entriesLiefert alle Ergebnis-Einträge

Beschreibung

array ldap_get_entries ( resource $Verbindungs-Kennung , resource $Ergebnis-Kennung )

Rückgabewert: im Erfolgsfall wird die gesamte Information des Ergebnisses in einem multidimensionalen Array zurückgegeben; im Fehlerfall FALSE.

Die ldap_get_entries() Funktion wird verwendet um das Lesen mehrfacher Einträge des Ergebnisses, angegeben mit Ergebnis-Kennung zu vereinfachen und danach werden die Merkmale und mehfachen Werte gelesen. Durch einen Funktionsaufruf wird die gesamte Information in einem multidimensionalen Array zurückgegeben. Die Struktur dieses Array sieht wie folgt aus.

Der Merkmal-Index wird in Kleinbuchstaben umgewandelt. (Verzeichnis-Server unterscheiden nicht zwischen Groß-/Kleinschreibung hinsichtlich der Merkmake, aber der Unterschied ist wichtig, wenn diese Merkmale als Array-Indizes benutzt werden.)

return_value["count"] = Anzahl der Einträge im Ergebnis
return_value[0] : bezieht sich auf Einzelheiten des ersten Eintrags

return_value[i]["dn"] =  DN des i-ten Eintrags im Ergebnis

return_value[i]["count"] = Anzahl der Merkmale im i-ten Eintrag
return_value[i][j]       = das j-te Merkmal des i-ten Eintrags im Ergebnis

return_value[i]["merkmal"]["count"] = Anzahl der Werte für das
                                      Merkmal im i-ten Eintrag
return_value[i]["merkmal"][j]       = der j-te Wert des Merkmals im i-ten
                                      Eintrag

Siehe auch ldap_first_entry() und ldap_next_entry()


17 BenutzerBeiträge:
- Beiträge aktualisieren...
Sebastien Troiani
29.01.2010 14:39
Looks like there is a limit on returned objects - only 1000 items are placed in the array
plonky at gmail dot com
7.04.2009 18:09
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);
?>
chl
11.03.2009 17:20
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"]=>
  ...
asohn at aircanopy dot net
21.09.2007 23:48
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);
}
?>
markus dot schabel at tgm dot ac dot at
21.02.2006 9: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;
}
?>
reuben dot helms at gmail dot com
7.02.2006 10:13
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.
Jim Granger
24.06.2005 23:27
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.
helmut dot patay at scandio dot de
22.04.2004 0:57
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;
    ...
}
Ovidiu Geaboc
13.11.2003 16:59
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);
mackstann / mack%at%incise%dot%org
4.09.2003 20:50
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;
}
reaper at sci dot fi
18.06.2003 15:09
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;
}
matt.s(remove)at(remove)aptalaska.net
16.04.2002 22:36
I noticed the same thing Ron did, except I couldn't get php to return the attribute values using numerical pointers at all.  I ended up using an eval() to pass in the associative name:

$ds=ldap_connect("ldapserver");

if ($ds) {

    $r=ldap_bind($ds); #bind to directory
    $sr=ldap_search($ds,"dc=domain,dc=net", "uid=user"); #search for user
   
    print  "Number of entires returned is " .ldap_count_entries($ds,$sr)."<p>";

    $info = ldap_get_entries($ds, $sr); #get the result
   
    print "Data for ".$info["count"]." items returned:<p>";

    for ($i=0; $i<$info["count"]; $i++) {  #loop though ldap search result
     
      print "dn: " . $info[$i]["dn"] . "<br>"; #print dn
   
      for ($ii=0; $ii<$info[$i]["count"]; $ii++) { #loop though attributes in this dn
        print "&nbsp;&nbsp;" . $info[$i][$ii] . ": "; #print attribute name
        $attrib = $info[$i][$ii]; #set attribute
        eval("print \$info[\$i][\"$attrib\"][0];"); #print attribute value

        print "<br>";
      }
     
      print "<br>";
    }
   
    ldap_close($ds);
   
} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
pmichaud at pobox dot com
10.02.2002 3:43
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.
c dot green at its dot uq dot edu dot au
17.08.2001 13:25
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;
oscara at hinux dot hin dot no
15.05.2001 18:51
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...
john at petbrain dot com
20.12.2000 19:24
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.
cbrent at orix dot com dot au
18.04.2000 7:03
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.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)