0

I'm using PHP to query users and their attributes in Active Directory. The problem I have is that the LDAP field for Department Manager is not only returning the user name, but also the FQDN (fully qualified domain name) path as shown below:

CN=User Name,OU=Users,OU=companyBranchOffice,OU=companyName,DC=subdomain,DC=domain,DC=com

The result is saved in a string, $depManager. How can I filter out only the user name (CN=)?

Thanks in advance!

EddyTheDove
  • 12,979
  • 2
  • 37
  • 45

3 Answers3

0

There is my simple (maybe not optimized) function to fetch informations from a DN :

<?php
function getInfosFromDN($dn)
{
    $regexCaptures = "/^(CN=.+),(OU=.+),(DC=.+)$/iU";

    $CN = preg_replace($regexCaptures, "$1", $dn);
    $OU = preg_replace($regexCaptures, "$2", $dn);
    $DC = preg_replace($regexCaptures, "$3", $dn);

    return array($CN, $OU, $DC);
}

list($CN, $OU, $DC) = getInfosFromDN("CN=User Name,OU=Users,OU=companyBranchOffice,OU=companyName,DC=subdomain,DC=domain,DC=com");
Guillaume Sainthillier
  • 1,655
  • 1
  • 9
  • 13
0

I suppose you are currently using ldap_get_entries to pull the sn/cn/ou/uid attribute? Probably you can experiment with an other of those (depending on you configuration, maybe uid) to only get the real user name. No need to preg_replacing.

Example:

$sr = ldap_search($ds, $dn, $filter) or die ("bummer");
$results = ldap_get_entries($ds, $sr);
var_dump($results);

Now you can see if there is any attribute in your database that hold the value for just the user name, and not the whole DN. If that doesn't work, you can always do it manually like Guillaume suggested.

SJDS
  • 312
  • 7
  • 19
  • I'm using ldap_get_entries with ldap_search as the second argument: $results = (($keep) ? ldap_search($mydap,$user_dn,'cn=*',$keep) : ldap_search($mydap,$user_dn,'cn=*')) or die('Error searching LDAP: '.ldap_error($mydap)); – Christer Tjernberg Mar 07 '17 at 12:13
  • You could try 2 things. First to filter on `'objectclass=*'`. Second to var_dump the results of ldap_search (e.g. via `ldap_get_entries`.) Added an example to my answer. – SJDS Mar 07 '17 at 23:34
0

There are different options you have there.

  • The first option is to do a separate LDAP-Query to fetch the LDAP-Entry for the given DN and retrieve the Users user-name from that
  • Then you can parse the string using either PHPs string-functions or a regex to fetch the part between the CN=and the ,
  • Or you can use f.e. Zend\Ldap\Dn like this:

    $dn = new \Zend\Ldap\Dn('CN=User Name,OU=Users,OU=companyBranchOffice,OU=companyName,DC=subdomain,DC=domain,DC=com');
    echo current($dn->get(0));
    // $dn->get(0) will return ['cn' => 'User Name']
    // so current($dn->get(0)) will return 'User Name'
    

Disclaimer: I'm one of the maintainers of Zend\Ldap

heiglandreas
  • 3,803
  • 1
  • 17
  • 23