Search code examples
phpphpldapadmin

php ldap get all(recursive) activedirectory users in a node


I have an active directory here how it looks:

enter image description here

Now I post a group name to ldap function and wants to get all users under this group..

I run this:

ldap_search($ldap_con, "DC=Company,DC=Intra", "(&(&(objectClass=user)(objectCategory=Person))(CN=*))");

it retrieves all users in domain, I just want to make it in specific group I tried(the users under the 'OU=Company Name' as seem in picture) these but none of them works..

ldap_search($ldap_con, "DC=Company,DC=Intra", "(&(&(objectClass=user)(objectCategory=Person))(CN=*,OU=Company))");
ldap_search($ldap_con, "DC=Company,DC=Intra", "(&(&(objectClass=user)(objectCategory=Person))(memberOf=OU=Company Name))");
ldap_search($ldap_con, "DC=Company,DC=Intra", "(&(&(objectClass=user)(objectCategory=Person))(memberOf=Kullanicilar,OU=Company Name))");

Even this not work:

ldap_search($ldap_con, "DC=Company,DC=Intra", "(&(&(objectClass=user)(objectCategory=Person))(OU=*))");

Do I have to use CN in search parameters ? how will I retrieve users in CN and OU in same query?


Solution

  • I found a way to accomplish my goal. ldap_search function required 3 parameters: ("ldap connection instance", "base node path, its value of distinguishedname attribute..", "and objects query with param its static, objectClass=user and objectCategory=Person is required to get an ad object as user object so..")

    Here is my function (this exp. retrieves the users in node you see above in question post):

    public function saveAllUsersInGroup($ldap_con, $groupname){
        $base_dn = $this->getmainAttribute();
        //exp: $groupname = "OU=Kullanicilar,OU=CompanyName,DC=Company,DC=Intra"
        $results1 = ldap_search($ldap_con, $groupname, 
             "(&(&(objectClass=user)(objectCategory=Person))(CN=*))",array("distinguishedname"));
        $userList = ldap_get_entries($ldap_con, $results1);
        unset($userList["count"]);
        $result = array();
        foreach($userList as $user)
            $result[] = $user["dn"];
        return implode("&",$result);
    } 
    

    It works for me. I hope this helps if someone needs the same.