Authenticating against an LDAP server consists of just connecting to the server then binding using your credentials. Here’s a couple functions I use to authenticate again LDAP. The first function, ldapauthenticated, takes your uid and password and attempts to bind to the LDAP server. It returns a bool, true you were successful, false you weren’t. Pretty simple. There are 2 constants I use in the function, LDAP_SERVER and LDAP_BASE_DN. These would need to be defined. LDAP_SERVER is your server’s host name. LDAP_BASE_DN would be something like ?¢‚Ǩ?ìdc=something, dc=company, dc=com”

function ldapauthenticated($uid, $password) {
/ldap will bind anonymously, make sure we have some credentials/
if ($uid != ”) {
$ldap = @ldap_connect(LDAP_SERVER);
$prot3 = @ldap_set_option($ldap,LDAP_OPT_PROTOCOL_VERSION,3);
if (isset($ldap) && $ldap != ” && $prot3) {
/* search for pid dn /
$result = @ldap_search($ldap, LDAP_BASE_DN, ‘uid=’.$uid, array(‘dn’));
if ($result != 0) {
$entries = @ldap_get_entries($ldap, $result);
$principal = $entries[0][‘dn’];
if (isset($principal)) {
/
bind as this user */
if (@ldap_bind($ldap, $principal, $password)) {
// Authenticate success
return true;
} else {
// Authenticate failure
return false;
}
} else {// User not found in LDAP
return false;
} // end: else: if (isset($principal))
ldap_free_result($result);
} else { // Error occured searching the LDAP
return false;
}
ldap_close($ldap);
} else { // Could not connect to LDAP
return false;
}
} else {
return false;
}
return false;
}

The second function, userauthenticated, does some setup if the user is authenticated against the LDAP server. You can see that if ldapauthenticated is successful a object (which I normally would not like to use) is setup. It’s a class I created for the specific system this code was taken from. Anyway, the most important function is the first one. The second one just shows how you can do a little setup for your users once they authenticate.

function userauthenticated ($uid, $password) {
if (ldapauthenticated ($uid, $password)) {
$user = new User ($uid);
if (!$user->id) {
$_SESSION[‘messages’] = “User/Password combination not found.”;
return false;
} else {
$_SESSION[‘user_id’] = $user->id;
$_SESSION[‘messages’] = “You are now logged in.”;
return true;
}
} else {
$_SESSION[‘messages’] = “LDAP authentication failed.”;
return false;
}
}