LDAP, or Lightweight Directory Access Protocol, is an application protocol for accessing and managing distributed directory information services. It is widely used to store user accounts, group information, and other related data. With LDAP, applications can quickly perform user authentication and contact lookups. Understanding how LDAP works is essential for implementing PHP LDAP searches.
Using LDAP in PHP is straightforward. First, ensure that the PHP LDAP extension is installed and enabled. You can check this with the following command:
<span class="fun">php -m | grep ldap</span>
If "ldap" does not appear, please install the appropriate extension based on your environment.
Before performing a search, you need to connect to the LDAP server. Here's an example:
$ldap = ldap_connect("ldap://your_ldap_server.com");
if ($ldap) {
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($ldap, "username", "password");
}
Replace your_ldap_server.com, username, and password with your actual server and credentials.
Once connected successfully, you can perform an LDAP search. Here's a basic example:
$searchBase = "ou=users,dc=example,dc=com";
$searchFilter = "(uid=john)";
$result = ldap_search($ldap, $searchBase, $searchFilter);
$entries = ldap_get_entries($ldap, $result);
print_r($entries);
Adjust ou=users,dc=example,dc=com and the filter (uid=john) as needed.
LDAP search results may include multiple entries. You can iterate through them as follows:
foreach ($entries as $entry) {
if (isset($entry['dn'])) {
echo "DN: " . $entry['dn'] . "\n";
echo "Email: " . $entry['mail'][0] . "\n";
}
}
This example extracts and displays the distinguished name (DN) and email address for each entry.
After completing operations, make sure to close the connection to free resources:
<span class="fun">ldap_unbind($ldap);</span>
By mastering the PHP LDAP search process — including server connection, query execution, and result handling — you can efficiently implement user authentication and data retrieval features. Follow best practices for security and performance to ensure stable and reliable applications. We hope this guide helps you smoothly integrate LDAP services into your PHP projects.