Among its many other capabilities, PHP also comes with afull-featured API to connect to, and communicate with, LDAP directoryservers. This article explores how PHP and LDAP can be used together,beginning with a crash course in LDAP basics and proceeding to a series ofsimple examples that demonstrate how PHP can be used to search an LDAPdirectory and format the results for the Web.
Now that all the requirements are in place, let's put together a simple PHP script to connect to the LDAP server and display the contents of the directory. Take a look at the following code.
<html>
<head>
</head>
<body>
<?php
// 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", "(cn=*)") or die ("Error in search
query");
// 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 "dn is: ". $info[$i]["dn"] ."<br>";
echo "first cn is: ". $info[$i]["cn"][0] ."<br>";
echo "first email address is: ". $info[$i]["mail"][0] ."<p>"; }
// print number of entries found
echo "Number of entries found: " . ldap_count_entries($conn, $result) .
"<p>";
// all done? clean up
ldap_close($conn);
?>
</body>
</html>
Run the script in your browser, and you should see something
like this: