17.5 Performing a Tree Search


You want to search more than just the current directory level, as ldap_list() does.

Technique

Use the ldap_search() function, which will search the entire LDAP tree of the specified directory:

 <?php // connect and bind $lh = ldap_connect("localhost")   or die("Cannot Connect"); ldap_bind($lh)   or die("Cannot Bind"); // Build the search and attributes we want $search_query = "sn=bro*"; $attributes = array("cn", "objectclass", "mail"); // Perform that thar query and load the results into an array $sth = ldap_search($lh, "o=Sterling's Company, c=US",                    $search_query, $attributes); $entries = ldap_get_entries($lh, $sth); ldap_free_result($sth); // Print out all the good information that we have collected echo "$entries[count] matching entries were found"; while ($idx < $entries[count]) {     echo 'Well ' . $entries[$idx][cn] . ' seems to have matched;';     echo ' if you want to talk to him his e-mail is ';     echo $entries[$idx][mail] .".\n<br>\n";     $idx++; } // close the connection ldap_close($lh); ?> 

Comments

The ldap_search() function searches an entire LDAP directory tree, as opposed to ldap_list() , which searches only the current directory. In this example, we connect to the LDAP server ( ldap_connect() ), and then bind for read access ( ldap_bind() without dn and password ). We then build up our search query ( $search_query ) and the attributes that we want to collect from the matches. After all this is done, we are ready to use the ldap_search() function to find the relevant entries, which we then retrieve with the ldap_get_entries() function. Finally, we have the results in an array for manipulation, and we simply use a while loop to process the array and print the relevant entries. When it is all done, the connection is closed.

Note in the synopsis that when it comes time to loop through the result array, we use $entries[count] instead of count($entries) . This is because the ldap_get_entries() function has a special key, count , that holds the number of entries in the array to process.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net