In this second, and concluding, article, dig deeper into PHP'sLDAP API by writing complex search queries and building a Web-basedadministration module to retrieve and modify entries from the LDAP directorytree.
In the first part of this article, I had written a simple PHP script to search the LDAP directory for a particular user. But real life is never that simple...
Let's suppose I want to search for my friend Joe from high school. Now, there are a million Joes in the world, and I would like to drill down to my Joe without having to navigate through a large set of results. The solution? A more complex search, which uses additional parameters to restrict the result set.
Take a look at the new search form,
<form action="search.php" method="POST">
<input type="text" name="cn" length="30"><br>
<input type="text" name="sn" length="30"><br>
<input type="text" name="email" length="30"><br>
<input type="submit" name="submit" value="Search">
which looks like this:
Once the form above is submitted, the data entered by the user is sent to the search script "search.php", which actually performs the query - take a look:
// specify the LDAP server to connect to
$conn = ldap_connect("localhost") or die("Could not connect to server");
// bind to the LDAP server specified above
$r = ldap_bind($conn) or die("Could not bind to server");
// start searching
// specify both the start location and the search criteria
// in this case, start at the top and return all entries $result =
ldap_search($conn,"dc=my-domain,dc=com", $query) or die("Error in search
// get entry data as array
$info = ldap_get_entries($conn, $result);
// iterate over array and print data for each entry
for ($i=0; $i<$info["count"]; $i++)
echo "<li>".$info[$i]["sn"]." - ".$info[$i]["mail"]." -
".$info[$i]["dn"]."</li>"; } echo "</ul>";
// print number of entries found
echo "Number of entries found: " . ldap_count_entries($conn, $result) .
// all done? clean up
The structure of the code is identical to that of the
examples in previous pages - with one important difference:
This search string, obviously with the variables replaced
with actual values, is passed to the ldap_search() function; it returns only those entries from the LDAP directory free which match *all* the parameters specified. Why? Because of my usage of the special AND operator, signified by the addition of the ampersand (&) to the beginning of the search string above.
Here's what the output looks like:
If your LDAP entries contain other attributes, it's just as easy to create more complex search queries - simply add more input fields to the search form, and update the search string above to use those attributes when searching the directory tree.
In case you were wondering, yes, you can also use logical OR (the | operator) or logical NOT (the ! operator) in your search queries - I'll leave that to you to play with.