We help IT Professionals succeed at work.

PHP LDAP Lookup

adznon
adznon asked
on
I have a PHP webpage that captures the username of the person connecting to it.

I now need to do a lookup in Active Directory to get the email address (SecurityPincipal.sAMAccountName)

I have had some success with the below code, in it will bind successfully with LDAP but does not return anything

<?php

//using ldap bind anonymously

// connect to ldap server
$ldapconn = ldap_connect("global.tesco.org")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding anonymously
    $ldapbind = ldap_bind($ldapconn);

    if ($ldapbind) {
        echo "LDAP bind anonymous successful...";

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

        $dn = "CN=Users,DC=name,DC=name,DC=org"; 
        $filter="(sAMAccountName=username)";
        $justthese = array("ou", "sn", "givenname", "mail");

        $sr=ldap_search($ldapconn, $dn, $filter, $justthese);

        $info = ldap_get_entries($ldapconn, $sr);

        echo $info["count"]." entries returned\n";

    } else {
        echo "LDAP bind anonymous failed...";
    }
}
?>

Open in new window

Comment
Watch Question

Fractional CTO
Distinguished Expert 2019
Commented:
This is a common question on EE + elsewhere. The trick to getting your programmatic code working correctly is to start with working command line code.

Working with command line tools is far easier to debug. Once you have your command line code working, then convert your working commands to programmatic calls.

There are many related guides online.

https://www.digitalocean.com/community/tutorials/how-to-manage-and-use-ldap-servers-with-openldap-utilities is a good one I just scanned.