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 "

Common Name: " . $data[$i]["cn"][0] . "


";
echo "Distinguished Name: " . $data[$i]["dn"] . "
";
//checking if discription exists
if (isset($data[$i]["description"][0]))
echo "Desription: " . $data[$i]["description"][0] . "
";
else
echo "Description not set
";
//checking if email exists
if (isset($data[$i]["mail"][0]))
echo "Email: " . $data[$i]["mail"][0] . "

";
else
echo "Email not set

";
}
// close connection
ldap_close($ds);
?>



No comments

Leave your comment

In reply to Some User
Captcha Image