PHP – LDAP Query AD Users

Overview

The below PHP script is an example of how to connect to Active Directory via LDAP and retrieve a list of users’ details.

If instead, you are looking to retrieve information on computer accounts in the domain. Take a look at this post

Requirements

To use this script your PHP web server will need the LDAP module installed,  you can verify the installation by creating a phpinfo file.

phpinfo.php

<?php
   phpinfo();
?>

When browsing to this web page you should see an LDAP section;

PHPInfo LDAP Section

If you don’t see an LDAP section in your phpinfo results you will need to install the php LDAP package, for example on Ubuntu / Debian;

# Install php5-ldap:
sudo apt-get install php5-ldap
# Reboot apache
/etc/init.d/apache2 restart

Variables to change

You will need to change the variables.

Line 4 - $ldap_password = 'AD_Password';
Line 5 - $ldap_username = '[email protected]';
Line 6 - $ldap_connection = ldap_connect("domain.tld");

Line 20 - $ldap_base_dn = 'DC=domain,DC=tld,DC=tld'; 

The Script

<?php

//LDAP Bind paramters, need to be a normal AD User account.
$ldap_password = 'AD_Password';
$ldap_username = '[email protected]';
$ldap_connection = ldap_connect("domain.tld");

if (FALSE === $ldap_connection) {
    // Uh-oh, something is wrong...
    echo 'Unable to connect to the ldap server';
}

// We have to set this option for the version of Active Directory we are using.
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die('Unable to set LDAP protocol version');
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0); // We need this for doing an LDAP search.

if (TRUE === ldap_bind($ldap_connection, $ldap_username, $ldap_password)) {

    //Your domains DN to query
    $ldap_base_dn = 'DC=domain,DC=tld,DC=tld';

    //Get standard users and contacts
    $search_filter = '(|(objectCategory=person)(objectCategory=contact))';

    //Connect to LDAP
    $result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter);

    if (FALSE !== $result) {
        $entries = ldap_get_entries($ldap_connection, $result);

        // Uncomment the below if you want to write all entries to debug somethingthing 
        //var_dump($entries);

        //Create a table to display the output 
        echo '<h2>AD User Results</h2></br>';
        echo '<table border = "1"><tr bgcolor="#cccccc"><td>Username</td><td>Last Name</td><td>First Name</td><td>Company</td><td>Department</td><td>Office Phone</td><td>Fax</td><td>Mobile</td><td>DDI</td><td>E-Mail Address</td><td>Home Phone</td></tr>';

        //For each account returned by the search
        for ($x = 0; $x < $entries['count']; $x++) {

            //
            //Retrieve values from Active Directory
            //

            //Windows Usernaame
            $LDAP_samaccountname = "";

            if (!empty($entries[$x]['samaccountname'][0])) {
                $LDAP_samaccountname = $entries[$x]['samaccountname'][0];
                if ($LDAP_samaccountname == "NULL") {
                    $LDAP_samaccountname = "";
                }
            } else {
                //#There is no samaccountname s0 assume this is an AD contact record so generate a unique username

                $LDAP_uSNCreated = $entries[$x]['usncreated'][0];
                $LDAP_samaccountname = "CONTACT_" . $LDAP_uSNCreated;
            }

            //Last Name
            $LDAP_LastName = "";

            if (!empty($entries[$x]['sn'][0])) {
                $LDAP_LastName = $entries[$x]['sn'][0];
                if ($LDAP_LastName == "NULL") {
                    $LDAP_LastName = "";
                }
            }

            //First Name
            $LDAP_FirstName = "";

            if (!empty($entries[$x]['givenname'][0])) {
                $LDAP_FirstName = $entries[$x]['givenname'][0];
                if ($LDAP_FirstName == "NULL") {
                    $LDAP_FirstName = "";
                }
            }

            //Company
            $LDAP_CompanyName = "";

            if (!empty($entries[$x]['company'][0])) {
                $LDAP_CompanyName = $entries[$x]['company'][0];
                if ($LDAP_CompanyName == "NULL") {
                    $LDAP_CompanyName = "";
                }
            }

            //Department
            $LDAP_Department = "";

            if (!empty($entries[$x]['department'][0])) {
                $LDAP_Department = $entries[$x]['department'][0];
                if ($LDAP_Department == "NULL") {
                    $LDAP_Department = "";
                }
            }

            //Job Title
            $LDAP_JobTitle = "";

            if (!empty($entries[$x]['title'][0])) {
                $LDAP_JobTitle = $entries[$x]['title'][0];
                if ($LDAP_JobTitle == "NULL") {
                    $LDAP_JobTitle = "";
                }
            }

            //IPPhone
            $LDAP_OfficePhone = "";

            if (!empty($entries[$x]['ipphone'][0])) {
                $LDAP_OfficePhone = $entries[$x]['ipphone'][0];
                if ($LDAP_OfficePhone == "NULL") {
                    $LDAP_OfficePhone = "";
                }
            }

            //FAX Number
            $LDAP_OfficeFax = "";

            if (!empty($entries[$x]['facsimiletelephonenumber'][0])) {
                $LDAP_OfficeFax = $entries[$x]['facsimiletelephonenumber'][0];
                if ($LDAP_OfficeFax == "NULL") {
                    $LDAP_OfficeFax = "";
                }
            }

            //Mobile Number
            $LDAP_CellPhone = "";

            if (!empty($entries[$x]['mobile'][0])) {
                $LDAP_CellPhone = $entries[$x]['mobile'][0];
                if ($LDAP_CellPhone == "NULL") {
                    $LDAP_CellPhone = "";
                }
            }

            //Telephone Number
            $LDAP_DDI = "";

            if (!empty($entries[$x]['telephonenumber'][0])) {
                $LDAP_DDI = $entries[$x]['telephonenumber'][0];
                if ($LDAP_DDI == "NULL") {
                    $LDAP_DDI = "";
                }
            }

            //Email address
            $LDAP_InternetAddress = "";

            if (!empty($entries[$x]['mail'][0])) {
                $LDAP_InternetAddress = $entries[$x]['mail'][0];
                if ($LDAP_InternetAddress == "NULL") {
                    $LDAP_InternetAddress = "";
                }
            }

            //Home phone
            $LDAP_HomePhone = "";

            if (!empty($entries[$x]['homephone'][0])) {
                $LDAP_HomePhone = $entries[$x]['homephone'][0];
                if ($LDAP_HomePhone == "NULL") {
                    $LDAP_HomePhone = "";
                }
            }

            echo "<tr><td><strong>" . $LDAP_samaccountname . "</strong></td><td>" . $LDAP_LastName . "</td><td>" . $LDAP_FirstName . "</td><td>" . $LDAP_CompanyName . "</td><td>" . $LDAP_Department . "</td><td>" . $LDAP_OfficePhone . "</td><td>" . $LDAP_OfficeFax . "</td><td>" . $LDAP_CellPhone . "</td><td>" . $LDAP_DDI . "</td><td>" . $LDAP_InternetAddress . "</td><td>" . $LDAP_HomePhone . "</td></tr>";
        } //END for loop
    } //END FALSE !== $result

    ldap_unbind($ldap_connection); // Clean up after ourselves.
    echo ("</table>"); //close the table

} //END ldap_bind

30 thoughts on “PHP – LDAP Query AD Users”

    • Hi,

      I don’t have a data set that large to test with, but I would imagine you will need a couple more ldap_set_option‘s at the top.

      LDAP_OPT_SIZELIMIT (integer)
      Specifies the maximum number of entries that can be returned on a search operation.

      Note: The actual size limit for operations is also bounded by the server’s configured maximum number of return entries. The lesser of these two settings is the actual size limit.

      LDAP_OPT_TIMELIMIT (integer)
      Specifies the number of seconds to wait for search results.
      Note: The actual time limit for operations is also bounded by the server’s configured maximum time. The lesser of these two settings is the actual time limit.

      Reply
  1. Good morning!!
    How can i sort the result by smaccountname for example?
    I don’t know how to create this cod.

    Thank you.

    Reply
  2. Hey I also tested it out and it worked fine but when I am trying to get the path of an image, which has the Attribue labeledURI.
    I replaced the Attribute from ‘homephone’ (line 163 &164) to ‘labeledURI’ but I get a reply that it is empty.
    I used sysinternals to this this but the programm shows me the path of the profile image.
    Any ideas?

    Reply
  3. Hi
    This is really good but what I need is to populate the dropdown with the users from the AD of specific OU like ITS Department

    Reply
    • Hi,

      You would need to change the base dn to filter based on the OU you are interested in. Stick the the result into a variable for use in your drop down list.

      $ldap_base_dn = ‘OU=ITDept,DC=domain,DC=tld,DC=tld’;

      Thanks
      Phil

      Reply
  4. This is the first time that I am authenticating with LDAP and I am lost with the values that are in the variable $ldap_base_dn.

    What to put in DC = domain? what is DC = tld?

    My search is returned empty.

    Reply
    • Hi Bruno,

      So you will need a user account in your Active Directory domain, just a standard user no admin rights is required.

      You will also need to know your domain name. The are many ways to get this, but f your computer is joined to the domain your are looking to query you could run the following in a command prompt.

      systeminfo | findstr /B /C:”Domain”

      So for example lets assume I know these values;

      AD Username = Bruno
      AD Password = Bruno1234$
      AD Domain = Bruno.com

      The scripts variables would look like this

      Line 4 – $ldap_password = ‘Bruno1234$’;
      Line 5 – $ldap_username = ‘[email protected]’;
      Line 6 – $ldap_connection = ldap_connect(“Bruno.com”);

      Line 20 – $ldap_base_dn = ‘DC=Bruno,DC=com’;

      If you domain has two bits at the end like Bruno.co.uk line 20 would instead look like this

      Line 20 – $ldap_base_dn = ‘DC=Bruno,DC=co,DC=uk’;

      DC stands from domain component in the world of LDAP
      TLD is top level domain. .com, .co.uk….

      I hope that helps?

      Thanks
      Phil

      Reply
      • I understand now, in my case my domain name is (rectvi.record.local) and in the variable $ ldap_base_dn = ‘DC = rectvi, DC = record, DC = local’;

        However, even with the changes it presents the following error: Warning: ldap_search (): Search: No such object in …

        Reply
  5. Hi Phill, can you help me to search data only same user, for example: how can i get Fist Name, Second Name, Email, Departament and more entries of only one user.

    Reply
    • I got Photos! but im sure theres a better way to do it

      //Home phone
      $LDAP_HomePhone = “”;

      if (!empty($entries[$x][‘thumbnailphoto’][0])) {
      $LDAP_HomePhone = $entries[$x][‘thumbnailphoto’][0];
      if (isset($entries[0][“thumbnailphoto”]) && isset($entries[0][“thumbnailphoto”][0])) {
      if ($LDAP_HomePhone == “NULL”) {
      $LDAP_HomePhone = “”;

      Then in the echo i have

      “” . ” . “”;

      I had no use for homephone so i changed that around instead of another entry

      Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.