PDA

View Full Version : Looking up users in ldap with php


arnyinc
02-27-2006, 04:02 PM
I'm just starting out integrating PHP with LDAP. The way our active directory is organized is OU=Accounts,OU=US,DC=mycorp,DC=com. The OU for "region" is different depending on your location. For example, someone in Canada would be OU=Accounts,OU=CA,DC=mycorp,DC=com. Using the code below, I can lookup a user if I know this location but I would never know this location until I looked them up (catch 22). :o

It appears that all users belong to the Domain Users group, but I can't figure out how to specify this as the base dn and get PHP to print out their information.


<?
$passeduser=strtolower($_SERVER["AUTH_USER"]);

list($dmn, $zid)=split("\\\\", $passeduser);

$ldap_server = "ldap://".$dmn.".mycorp.com";
$auth_user = "user@mycorp.com";
$auth_pass = "fake";

//This base dn doesn't work
//$base_dn = "CN=Domain Users,CN=Users,DC=mycorp,DC=com";

//This base dn works
$base_dn = "OU=Accounts,OU=US,DC=mycorp,DC=com";
$filter = "(&(objectClass=user)(objectCategory=person)(cn=myid))";

if (!($connect=ldap_connect($ldap_server)))
die("Could not connect to ldap server");
else
echo "Connected to ".$dmn."\n<br>";

if (!($bind=ldap_bind($connect, $auth_user, $auth_pass)))
die("Unable to bind to server");
else
echo "Successful bind to ".$dmn."\n<br>";

if (!($search=ldap_search($connect, $base_dn, $filter)))
die("Unable to search ldap server");
else
echo "Successful search\n<br>";

$info=ldap_get_entries($connect, $search);


for ($i=0; $i<=count(info)-1; $i++){
echo "Name is: ". $info[$i]["name"][0]."<br>";
echo "Display name is: ". $info[$i]["displayname"][0]."<br>";
echo "Email is: ". $info[$i]["mail"][0]."<br>";
echo "Address is: ". $info[$i]["streetaddress"][0]."<br>";
echo "Telephone number is: ". $info[$i]["telephonenumber"][0]."<br>";
echo "Primary Group ID is: ". $info[$i]["primarygroupid"][0]."<br>";

for ($j=0; $j<count($info[$i]["member"])-1; $j++)
echo "Members: ". $info[$i]["member"][$j]."<br>";
}


echo "</p>\n";

ldap_unbind($connect);
?>

arnyinc
02-27-2006, 04:23 PM
Nevermind, I think I got it. Of course I spent a few hours the past 3 days looking for the answer and the second I post this, I figure it out.

I added these lines in:

<?
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
?>

This is specific to active directory when querying windows 2003. I've seen these options all over the place, but I just assumed I didn't need them since I was able to query against a more specific DN.