Link to home
Start Free TrialLog in
Avatar of kmgish
kmgish

asked on

Get all departments from Active Directory with PHP and ADLDAP

I am trying to display a simple list of all departments in our organization by querying Active Directory, with PHP, using the ADLDAP Class.  I know how to display information based on users, but not by departments. Alternatively I have tried to display just the departments by running an infoCollection query on all users, but I've been unsuccessful filtering duplicate departments.

Here's the output I'm trying to achieve:

1. Accounting
2. Corporate
3. Human Resources
4. Information Technology
5. Marketing
6. ...

Here is my code so far:

include ('/var/www/html/ldap/adLDAP.php');
        try {
		    $adldap = new adLDAP();
        }
        catch (adLDAPException $e) {
            echo $e; 
            exit();   
        }
	
$usernames = $adldap->user()->all();
$users = array();
$count= 0;
foreach ($usernames as $username)
{

$result=$adldap->user()->infoCollection($username, array("department"));	
$department = $result->department;
if (($department !='') && ($department != $department2))  {
$count++;

echo $count . ". " . $department . "<br>"; 

$department2 = $department;
} 

} 

Open in new window


Thank you
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

What about this code?
include ('/var/www/html/ldap/adLDAP.php');
try {
	$adldap = new adLDAP();
}
catch (adLDAPException $e) {
	echo $e; 
	exit();   
}
	
$usernames = $adldap->user()->all();
$users = array();
$count= 0;
$departments = array();
foreach ($usernames as $username)
{
	$result=$adldap->user()->infoCollection($username, array("department"));	
	$departments[] = $result->department;
} 

echo "Total departments : " . count($departments);
echo "<pre>";
print_r($departments);
echo "</pre>";

Open in new window

Avatar of kmgish
kmgish

ASKER

Hi JulianH,

Thanks for your response, but unfortunately, your solution is still printing duplicate departments.

Mark
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kmgish

ASKER

Yeah, that's pretty close to exactly what I need.  Thanks!
Avatar of kmgish

ASKER

Quick question through: how do I remove the key from the printed results?  I need to use the results in a form select dropdown.

Right now it's returning: [Information Technology] => Information Technology

I need to be able to separate out each department, so I can wrap html tags around them.

Thanks
Use a foreach loop
<select name="departments">
<?php
foreach($departments as $value) {
  echo <<< OPTION
      <option value="{$value}">{$value}</option>
OPTION;
}
?>
</select>

Open in new window

Avatar of kmgish

ASKER

Perfect!!!  Thank you very much!!!
You are most welcome - good luck with your project.