I know it’s crazy, to communicate with LDAP-server using ADSI LDAP Provider and ADO in PHP but sometimes you have to do crazy things.

The Active Directory Service Interfaces (ADSI) Lightweight Directory Access Protocol (LDAP) provider implements OLE DB interfaces that allow you to use ActiveX Data Objects (ADO) which are a set of Component Object Model (COM) objects that allows us to access objects in LDAP compliant directories such as Microsoft Active Directory.



PHP has a COM extension/class that is only available for the Windows version of PHP.

First you have to create an «ADODB.Connection», and set its Provider to «ADsDSObject» and open that connection by executing the «Open()»-function as shown in this example:

<?php

$conn = new \COM('ADODB.Connection');
$conn->Provider = "ADSDSOObject";
$conn->Open("Empirio AD Provider", 'username@empirio.local', 'password');

The «Open()»-function take 3 arguments, the first one is the connection name it must be a string, even an empty string "" is fine. In case you want to authenticate with the server you put the username as second parameter and password as the 3rd one. Those two parameters are optional.

After we have done that it’s time to build the query, in this case we are going get a list of all the users under a specific container (OU).

The query is composed of four elements separated by semicolons in the following format:

<LDAP://server/adsidn>;ldapfilter;attributes;scope

  • server: is the name (or IP address) of the server hosting the directory.
  • adsidn: is the distinguished name (DN) of the starting point for your query expressed ADsPath format with "/" separators and the root of the namespace to the left. You can also use an X.500 style attributed name format with the relative distinguished names separated by commas and the root of the name space to the right.
  • ldap filter: is the LDAP filter string
  • attributes: is a comma separated list of names of the attributes to be returned for each row in the recordset.
  • scope: is either: base, onelevel, or subtree.

Here is the example of the query I’m going to use:

<?php
// ...

$ADsPath    = "LDAP://dc-empirio-01/CN=Users,DC=empirio,DC=local";
$filter     = "(&(objectCategory=person)(objectClass=user))";
$attributes = "name,distinguishedName,sAMAccountName";
$scope      = "subTree";

$query      = '<' . $ADsPath . '>;' . $filter . ';' . $attributes . ';' . $scope;

It does not need much explaining. Now it’s time to execute the query and get back the result like so:

<?php
// ...

$result = $conn->Execute($query);
$count  = $result->RecordCount();

while (!$result->eof()){
    echo $result['sAMAccountName'] . '<br>';

    $result->MoveNext();
}

The result returned is an «ADODB.Recordset» and you iterate using the «while()»-function in PHP. All the available methods for «ADODB.Recordset» you can find here.