PHP code to search Windows Active Directory (via LDAP)

Following sample PHP code will connect to your local (or remote) Active Directory Domain Controller (LDAP server) and return all object with specified OU:

  • Number of objects found
  • Common Name
  • Distinguished Name
  • Description (if exists)
  • Primary Email Address (if exists)

Be aware that LDAP support by default is not installed in PHP. For instructions on how to install it check here.

 
<?php
// -------------- CHANGE VARIABLES TO SUIT YOUR ENVIRONMENT  --------------
//LDAP server address
$server = "ldap://192.168.1.55";
//domain user to connect to LDAP
$user = "This email address is being protected from spambots. You need JavaScript enabled to view it.";
//user password
$psw = "password";
//FQDN path where search will be performed. OU - organizational unit / DC - domain component
$dn = "OU=Accounts,OU=My Company,DC=mydomain,DC=com";
//Search query. CN - common name (CN=* will return all objects)
$search = "CN=*";                    
// ------------------------------------------------------------------------
echo "<h2>php LDAP query test</h2>";
// connecting to LDAP server
$ds=ldap_connect($server);
$r=ldap_bind($ds, $user , $psw); 
// performing search
$sr=ldap_search($ds, $dn, $search);
$data = ldap_get_entries($ds, $sr);    
echo "Found " . $data["count"] . " entries";
for ($i=0; $i<$data["count"]; $i++) {
 echo "<h4><strong>Common Name: </strong>" . $data[$i]["cn"][0] . "</h4><br />";
 echo "<strong>Distinguished Name: </strong>" . $data[$i]["dn"] . "<br />";
 //checking if discription exists 
 if (isset($data[$i]["description"][0])) 
 echo "<strong>Desription: </strong>" . $data[$i]["description"][0] . "<br />";
 else 
 echo "<strong>Description not set</strong><br />";
 //checking if email exists
 if (isset($data[$i]["mail"][0]))
 echo "<strong>Email: </strong>" . $data[$i]["mail"][0] . "<br /><hr />";
 else 
 echo "<strong>Email not set</strong><br /><hr />";
 }
 // close connection
 ldap_close($ds);
?>
 



Newsletter

Subscribe to receive occasional updates on new posts.
Your email will not be used for any other purpose and you can unsubscribe at any time.
Please wait