Current Location: Home> Latest Articles> Comprehensive PHP LDAP Search Guide: From Connection to Result Handling

Comprehensive PHP LDAP Search Guide: From Connection to Result Handling

gitbox 2025-08-08

What is LDAP and Its Uses

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.

Integrating PHP with LDAP

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.

Establishing an LDAP Connection

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.

Executing an LDAP Search

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.

Processing LDAP Search Results

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.

Closing the LDAP Connection

After completing operations, make sure to close the connection to free resources:

<span class="fun">ldap_unbind($ldap);</span>

Summary

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.