Tuesday, November 21, 2006

How to validate user against LDAP using PHP?

//SCRIPT TO VALIDATE USER AGAINST LDAP

// using ldap bind *** NOTE the uid *****
$ldaprdn = 'uid=USERID,dc=DCVALUE,dc=DCDOMAIN'; // ldap rdn or dn
$ldappass = 'PASSWORD'; // associated password

// connect to ldap server
$ldapconn = ldap_connect("CONNECTIONSTRING");

if(!$ldapconn)
{
echo "Could not connect to LDAP server.";
exit;
}

ldap_set_option($ldapconn, LDAP_OPT_SIZELIMIT, 0); // Set Size Limit to 0
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); //Set Protocol Version to 3

if ($ldapconn) {

$bind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
if(!$bind)
{
echo "LDAP server bind error.";
}

//Search on the LDAP Directory
$base_dn = "BASEDNVALUE";
$filter = "uid=USERID";
$inforequired = array("uid","mail","cn","sn"); //information required from the LDAP directory

$result = ldap_search($ldapconn,$base_dn,$filter,$inforequired); //search LDAP Directory

//Get the Search Result
$info = ldap_get_entries($ldapconn,$result);
if(!$result)
{
echo "Anonymous Search Failed";
}
if($info["count"] == 0)
{
echo "No records found";
}

if($info["count"] > 1)
{
echo "More than one such user - report to CITS";
exit;
}

//Login again with the username and password posted to check authentication
$user_dn = $info[0]["dn"];
$bind = @ldap_bind($ldapconn,$user_dn,$_SERVER['PHP_AUTH_PW']);
if(!$bind)
{
echo 'Bind failed. User Not Authenticated';
exit;
}

$login_user_id=$etype . $info[0]["uid"][0];
}

No comments: