How To Do An LDAP Search Using PHP

To perform an LDAP search using PHP, you can use the ldap_search() function. Here’s an example of how to use it:

<?php
// connect to LDAP server
$ldapconn = ldap_connect("ldap://ldap.example.com") or die("Could not connect to LDAP server.");

// bind to LDAP server with a privileged account
$ldapbind = ldap_bind($ldapconn, "cn=admin,dc=example,dc=com", "adminpassword") or die("Could not bind to LDAP server.");

// specify the base DN for the search
$base_dn = "ou=Users,dc=example,dc=com";

// specify the search filter
$filter = "(objectClass=inetOrgPerson)";

// specify the attributes to retrieve
$attributes = array("cn", "givenName", "sn", "mail");

// perform the search
$search = ldap_search($ldapconn, $base_dn, $filter, $attributes);

// retrieve the search results
$results = ldap_get_entries($ldapconn, $search);

// loop through the results and print them out
for ($i = 0; $i < $results["count"]; $i++) {
    echo "CN: " . $results[$i]["cn"][0] . "<br>";
    echo "Given Name: " . $results[$i]["givenname"][0] . "<br>";
    echo "Last Name: " . $results[$i]["sn"][0] . "<br>";
    echo "Email: " . $results[$i]["mail"][0] . "<br>";
}

// close LDAP connection
ldap_close($ldapconn);
?>

In this example, we’re connecting to an LDAP server, binding with a privileged account, specifying the base DN for the search, the search filter, and the attributes to retrieve. We then perform the search with ldap_search() and retrieve the results with ldap_get_entries(). Finally, we loop through the results and print them out. Don’t forget to close the LDAP connection when you’re done.

Leave a Reply

Proudly powered by WordPress | Theme: Code Blog by Crimson Themes.