How to authenticate using LDAP with config file in PHP

Authenticate using LDAP in PHP

login.php


<?php
require_once 'config.php';
/**
 * Created by Alobin Technologies
 */
if(isset($_POST['username']) && isset($_POST['password'])) {
$ldapServer = $config["LDAP_HOST"]; // ldap://alobin.com

$ldap = ldap_connect($ldapServer, $config["LDAP_PORT"]); // LDAP identifier
$username = $_POST['username']; // get the username entered by user
$password = $_POST['password']; // get the password entered by user 

$ldaprdn = $config["LDAP_DOMAIN"].'\\'.$username; //'alobin' . "\\" . $username;

ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);

$bind = @ldap_bind($ldap, $ldaprdn, $password);

if ($bind) { // if bind successful
$filter="(sAMAccountName=$username)"; // setting the filter 
$result = ldap_search($ldap,$config["LDAP_BASE_DN"],$filter); //LDAP_BASE_DN = "dc=alobin,dc=COM"
$entry = ldap_first_entry($ldap, $result);

$attrs = ldap_get_attributes($ldap, $entry);

echo $attrs["count"] . " attributes held for this entry:<p>";

for ($i=0; $i < $attrs["count"]; $i++) {
echo $attrs[$i] . "<br />";
}
@ldap_close($ldap);
} else {
$msg = "Username / Password invalid.";
echo $msg;
}

}else{
?>
<form action="#" method="POST">
<label for="username">Username: </label><input id="username" type="text" name="username" />
<label for="password">Password: </label><input id="password" type="password" name="password" />
<input type="submit" name="submit" value="Submit" />
</form>
<?php } ?>

config.php

<?php
$config = array (
	'LDAP_HOST' => 'ldap://mydomain.com',
	'LDAP_PORT' => 387,
	'LDAP_DOMAIN' => 'mydomain.com',
	'LDAP_BASE_DN' => 'dc=MYDOMAIN,dc=COM'
);
?>

Leave a Reply