PHP LDAP Lookup

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

adznonAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David FavorLinux/LXD/WordPress/Hosting SavantCommented:
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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
LDAP

From novice to tech pro — start learning today.