简体   繁体   中英

Query Active Directory Info using LDAP and PHP

I have a question in regards to LDAP implementation using PHP. I just recently started reading up on LDAP and am still having trouble understanding how it works. I am developing a new application that will grant access to users only if they are found in Active directory. The code I have posted below determines if the username and password the user enters is in Active Directory. This code works, however now I would like to pull the first name of the user based on what credentials were entered. The reason I would like to pull this information is so that when the user logs in they are redirected to another page (ie. dashboard.php) that will display content and the phrase "Welcome "First Name of User". I am just not sure how I would have to go about pulling this information. If anyone could provided feedback on how I should go about doing this it would be greatly appreciated.

Connecting to LDAP sever:

<?php
$ldaphost = "name of host"; //LDAP Host
$ldapport = 389; //LDAP Port Number                

$ldapconn = ldap_connect($ldaphost, $ldapport); //Connect to LDAP Host on LDAP Port Number

// Check LDAP connection
if(!$ldapconn) {
    die("Unsuccessful connection to " . $ldaphost . " on port " . $ldapport . "<br />");    
} 
?>

Validate if user is in Active Directory:

<?php
include 'ldap_connect.php';

$username = $_POST['username'];
$password = $_POST['password'];

$ldapbind = ldap_bind($ldapconn, $username, $password);

if ($ldapbind) {
    header("Location: ../dashboard.php");
} else {
    print "Access Denied!";
}
?>

You will have to do an ldap_search for the user to get the attributes of the user.

Something like this:

$ldapresults = ldap_search($ldapconn, $baseDn, 'samAccountName=' . $username, array('sn'), 0, 0, 10);
if (! $ldapresults) {
    die('No results found');
}
$results = ldap_get_entries($ldapconn, $ldapresults);
var_dump($results);

You should then see the content of $result.

Perhaps you will have to play around with $baseDn , the filter ( samAccountName=$username ) and the attributes retrieved ( array('sn') ) to get the values you are looking for right.

I've created a gist that does ldap-authentication and retrieval of user-information in one go. Have a look at https://gist.github.com/heiglandreas/5689592

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM