ViaThinkSoft CodeLib
This article is in:
CodeLib → Programming aids → PHP
$cfg_ldap_server = 'ldap://server.company.local';
$cfg_ldap_port = 389;
$cfg_ldap_base_dn = 'DC=COMPANY,DC=local';
$cfg_ldap_username = 'myuser@company.local';
$cfg_ldap_password = 'foobar';
function ad_check($email, $password) {
global $cfg_ldap_server;
global $cfg_ldap_port;
global $cfg_ldap_base_dn;
global $cfg_ldap_username;
global $cfg_ldap_domain;
global $cfg_ldap_password;
// Connect to the server
if (!empty($cfg_ldap_port)) {
if (!($ldapconn = @ldap_connect($cfg_ldap_server, $cfg_ldap_port))) throw new OIDplusException('Cannot connect to LDAP');
} else {
if (!($ldapconn = @ldap_connect($cfg_ldap_server))) throw new OIDplusException('Cannot connect to LDAP');
}
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
// Login in order to search for the user
if (!empty($cfg_ldap_username)) {
if (!empty($cfg_ldap_password)) {
if (!($ldapbind = @ldap_bind($ldapconn, $cfg_ldap_username, $cfg_ldap_password))) throw new OIDplusException('Cannot login to LDAP');
} else {
if (!($ldapbind = @ldap_bind($ldapconn, $cfg_ldap_username))) throw new OIDplusException('Cannot login to LDAP');
}
} else {
if (!($ldapbind = @ldap_bind($ldapconn))) throw new OIDplusException('Cannot login to LDAP');
}
// Search the user using the email address
if (!($result = @ldap_search($ldapconn,$cfg_ldap_base_dn, '(&(objectClass=user)(cn=*))'))) throw new OIDplusException('Error in search query: '.ldap_error($ldapconn));
$data = ldap_get_entries($ldapconn, $result);
$found_username = null;
for ($i=0; $i<$data['count']; $i++) {
if ((isset($data[$i]['mail'][0])) && ($data[$i]['mail'][0] == $email)) {
$found_username = $data[$i]['userprincipalname'][0];
}
}
if (is_null($found_username)) return false;
// Login as the new user in order to check the credentials
//ldap_unbind($ldapconn); // commented out because ldap_unbind() kills the link descriptor
if ($ldapbind = @ldap_bind($ldapconn, $found_username, $password)) {
//ldap_unbind($ldapconn);
ldap_close($ldapconn);
return true;
} else {
return false;
}
}
var_dump(ad_check('bob@example.com', 'helloworld'));
Daniel Marschall
ViaThinkSoft Co-Founder
ViaThinkSoft Co-Founder