How to search in LDAP

$ldapServer = 'ldap://ldap_server.domain.me';
$ldapPort = 389;
$ldapBaseDn = 'cn=users,dc=ldap_server,dc=domain,dc=me'; // Replace with your base DN

// Connect to the LDAP server
$ldapConn = ldap_connect($ldapServer, $ldapPort);

if (!$ldapConn) {
    echo "Failed to connect to the LDAP server";
    exit;
}

// Set LDAP options
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);

// Search for all users
$searchFilter = '(&(objectClass=person)(shadowexpire=-1))'; // Modify the filter to match your user schema
$attributes = array('dn','uid','sn','mail','displayname','gecos','departmentnumber'); //optional
$searchResults = ldap_search($ldapConn, $ldapBaseDn, $searchFilter, $attributes);

// Retrieve user entries
$users = ldap_get_entries($ldapConn, $searchResults);
print_r($users);

if ($users['count'] > 0) {
    for ($i = 0; $i < $users['count']; $i++) {
        $username = $users[$i]['displayname'][0];
        $fullname = $users[$i]['gecos'][0];
        echo "Username: $username, Full Name: $fullname<br>";
    }
} else {
    echo "No users found.";
}

// Close the LDAP connection
ldap_unbind($ldapConn);
Tagged:
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!