PHP Active Directory Search

I have redone my PHP Active directory search script. This is ideal if you need a company directory! why not use the data you already have!!!

Download here PHP Active Directory Search Script

php ad search screenshot
Just add the fully qualified domain name of your domain controller (host), the domain dn ( if your domain was beanz.meanz.heinz.com for example your dn would be DC=beanz,DC=meanz,DC=heinz,DC=com ) supply the username and password of a user in your domain, this user does not need to be a member of any group, as long as the account isn’t disabled. Then your off!

You can add active directory attributes to the $search_fields array to change what you can search on
You can add which active directory attributes are displayed in the result by adding to the $return_fields array
the key for these array is the Human readable version (i.e. what will be displayed) so if your using custom attributes you can show them as a friendly name.

Remember this wont work, with out the php LDAP module enabled, this can be easily done by uncommenting the module in your php.ini

<?php
// CONFIGURATION START
$config = array		('host' 			=> 'domaincontroller.domain.com',
 				'dn'	 			=> 'DC=domain,DC=com',
 				'username'			=> 'myusername@domain.com',
  				'password'			=> 'password',
 				'color1' 			=> '#DDDDDD',
 				'color2' 			=> '#FFFFFF',
 				);
// $search_fields ,  select which AD fields you want to search on
$search_fields=array('First Name' 		=> 'givenname',
 				 'Last Name' 		=> 'sn',
 				 );
//$return_fields , select which AD fields you wish to have displayed in the results
$return_fields=array('Display Name' 	=> 'displayname',
 				'First Name' 		=> 'givenname',
 				'Last Name' 		=> 'sn',
 				'Telephone Number' 	=> 'telephonenumber',
 				'Email Address' 	=> 'mail',
 				'Company' 			=> 'company',
 				 );
//CONFIGURATION END
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns=" http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>ACTIVEDIRECTORY SEARCH TOOL </title>
<style type="text/css">
<!--
body,td,th {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 10px;
}
-->
</style></head><body>
<form id="form1" name="form1" method="post" action="">
<?php
foreach ($search_fields as $key => $value)
  	  { ?>
  <label>
<b><?php echo $key; ?></b> <input name="<?php echo $value; ?>" type="text" id="givenname" />
  </label>
<?php } ?>
  <label>
  <input name="Search" type="submit" id="Search" value="Search" />
  </label>
</form>
<?php
$ldap_search='';
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
foreach ($search_fields as $item => $value) //build filter
 	{
 	if (empty($_POST[$value]))
 		{
 		 $filter[$value]="($value=*)";
 		} else {
 		 $filter[$value]="($value=$_POST[$value])";
 		}
 	$ldap_search=$ldap_search.$filter[$value];
 	}
 $attrs=array();
 foreach ($return_fields as $item => $value) //build attr array
 	{
 	$attrs[]=$value;
 	}
 $ldap_search='(&'.$and.$ldap_search.')';
$ad = ldap_connect($config['host'])
      or die( "Could not connect!" );
// Set version number
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3)
     or die ("Could not set ldap protocol");
ldap_set_option($ad, LDAP_OPT_REFERRALS,0)
 or die ("could no se the ldap referrals");
// Binding to ldap server
$bd = ldap_bind($ad, $config['username'], $config['password'])
      or die ("Could not bind");
// Create the DN
// Specify only those parameters we're interested in displaying
// Create the filter from the search parameters
$search = ldap_search($ad, $config['dn'], $ldap_search, $attrs)
          or die ("ldap search failed");
$entries = ldap_get_entries($ad, $search);
if ($entries["count"] > 0) {
$row_count = 0;
?>
No of results = <?php echo $entries["count"] ?>
</p>
<table width="100%" border="1">
  <tr>
  	<?php
 foreach ($return_fields as $item => $value)
 	{
 		?><th><?php echo $item ?></th><?php
 	}
 ?>
  </tr><? for ($i=0; $i<$entries["count"]; $i++) {
  $row_color = ($row_count % 2) ? $config['color1'] : $config['color2'];
  ?>
  <tr bgcolor="<?php echo $row_color ?>">
    <?php
 foreach ($return_fields as $item => $value)
 	{
 	if (isset ($entries[$i][$value][0]))
 		{
 		if ($value == 'mail') // do i need a mailto: link ?
 			{
 			echo "<td><a href=\"mailto:" .$entries[$i][$value][0]. "\">" .$entries[$i][$value][0]. "</a></td>" ;
 			} else {
 			echo '<td>'.$entries[$i][$value][0].'</td>';
 			}
 		} else {
 		echo '<td></td>'; //fial not set output empty cell
 		}
 	}
 ?>
 </tr>
<?
$row_count++;
 }
?>
</table>
<?
} else {
   echo "<p>No results found!</p>";
}
ldap_unbind($ad);
}
?>
<center><small><a href="http://www.james-lloyd.com">script by James Lloyd</a></small></center></html>
  1. sam s
    February 19th, 2009 at 14:36 | #1

    is it possible to modify user’s password in active directory using php?

  2. February 19th, 2009 at 14:46 | #2

    Yes and its simple ish, though you need to set up LDAPS (secure ldap ) access on you DC, which you can do just by installing a CA on that server

  3. sam s
    June 9th, 2009 at 11:48 | #3

    Nice script, how do you search just for users who have an active account? for example, if i click the search button w/o filling in the two fields, it lists ALL users.

  4. June 9th, 2009 at 12:20 | #4

    Whether an account is disabled or not depends on the userAccountControl field if this field is set to 514 then the account is a normal account that has been disbaled, disabled.

    However many different flags can be set by this field. Check out http://support.microsoft.com/kb/305144 for more info.

    However

    change line 67 to read

    $ldap_search=’(&’.$and.$ldap_search.’(userAccountControl=514))’;

    That should only display enabled accounts, please note I currently have no system to test that on.

  5. major
    June 15th, 2009 at 09:12 | #5

    Thanks, this is an excellent script.

    I have modified it a little bit to include user pictures from the thumbnailPhoto attribute.(I am a PHP noob, so my modification may not be the best)

    However, I do have a couple of questions:

    One is similar to sam s above, how can I list just users that have an ‘email’ account?

    The other question is how can I ‘hide’ a column?
    I am retrieving the distinguishedname of the user so I can look up their account on another page to pull their picture but I don’t want to display their distinguishedname on the web page.

    Thanks again.
    major

  6. June 15th, 2009 at 09:55 | #6

    I would stick an
    < --- insert after line 103 --->
    if (!empty($entries[$i]['mail'][0]))
    {
    < --- ---->

    < --- insert after line 114 --->

    }

    < --- --->

    you can add or hide columns by changing the $return_fields array at the top. Note the index is the “Nice Display name” and the key is the ldap field.

    Again no test rig at the moment so this is off the top of my head.

    If there is interest in this perhaps I could make something a lot more user friendly. Will monitor the traffic to this page.

  7. major
    June 15th, 2009 at 11:56 | #7

    Thanks, the retrieve only users with a mailbox fix worked perfectly.

    However, your other fix won’t work for me, I don’t think anyway.

    I need the script to still pull the distinguishedName attribute. I then send the distinguishedName to another php page through the URL ‘$_GET’ function.

    The other page then uses the distinguishedName of that user to look up the thumbnailPhoto and then displays it with the correct Header Content-Type.

    Again, my php knowledge is limited so if I am doing this incorrectly please let me know.

    Thanks!
    Major

  8. June 15th, 2009 at 12:51 | #8

    ah ha sorry I’m with you now!

    with out a complete new script and explaining it war & peace style I suggest you take a look at the ldap functions in php.net and the examples in the comments. What your talking about is straight forward.

  9. major
    June 16th, 2009 at 06:56 | #9

    Ok, I’ll look into it.

    Thanks again!

    Major

  10. Glitch
    August 18th, 2009 at 12:37 | #10

    how would i modify that script to pull just the Pictures and names from active directory? i am currently creating a slide show in drupal and i need to pull one picture at a time from AD and display it with the name associated with it, then pause then pull the next one. I have pretty much zero php knowledge and im working on creating this feature from copy and pasting scripts online. if you could advise, youd be my hero :)

  11. E7130
    November 3rd, 2009 at 13:18 | #11

    The only issue I see with it is that depending on the number of fields you are searching on it will only show you that number. For example, if you have givenname, sn, and physicaldeliveryofficename as your search criteria and someone doesn’t have the Office field filled in active directory they will not be searchable even by just searching on their givenname.

    Also having a drop down menu for search filters and then a textbox to the right of it would be better if you are using more filters.

  12. E7130
    November 4th, 2009 at 13:22 | #12

    Also your code does not leave open for keyword search.

  13. November 4th, 2009 at 13:50 | #13

    Only designed really to be a Proof of Concept. I have a much more sophisticated one some where with loads more features such as contact export etc.

  14. Andre
    November 26th, 2009 at 05:59 | #14

    tks a lot

  15. Piotr
    December 29th, 2009 at 13:09 | #15

    @James
    Is it possible to search by multiple userAccountControl property numbers such as a 512 and 65536 and have it show the results?

  16. Aurelien
    March 5th, 2010 at 07:19 | #16

    Hi,

    Can i have the script please ?
    The link : http://blog.james-lloyd.com/wp-content/uploads/2007/11/adsearchphp.txt is dead.

    Thanks in advance for the script

    JP

  1. No trackbacks yet.