I’ve found it necessary to do some searching of LDAP on a Windows server from a PHP script. It took a while to compile everything I needed, and I thought it’d be helpful if someone else had this code for their use. Read on to find out how to perform an LDAP search against AD.
function connectLDAP($server,$user,$password) { // Issue the connect command $ad_connect=ldap_connect($server) or die ("Could not connect to LDAP"); // These options are required for MS Active Directory ldap_set_option($ad_connect, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($ad_connect, LDAP_OPT_REFERRALS, 0); // Bind to AD with the username and password $ds_connect = ldap_bind($ad_connect,$user,$password) or die("Couldn't bind to AD!"); // Return handler return $ad_connect; } function disconnectLDAP($handle) { // Disconnect from the server ldap_unbind($handle); } function searchLDAP($ad,$query,$root,$sort) { // Query the LDAP server // Future: Want adjust the array on the fly later, such as objectclass $sr=ldap_search($ad, $root, $query); // If a sort field was requested, adjust the list if ($sort) { $st=ldap_sort($ad, $sr, $sort); } // Generate the array, and return $info = ldap_get_entries($ad, $sr); return $info; } $ad = connectLDAP($AD_Server,$AD_User,$AD_Password); $query = "(&(objectClass=person)(SAMAccountName=*)"; // Put whatever you want here $sort = ""; $info = searchLDAP($ad, $query, $AD_Root, $sort); if ($info["count"]>0) { // $info is an array } disconnectLDAP($ad);
The above is a basic search string. What is important to note is how the array works. It is a multi-dimensional array. To access data, you will need to cycle through the fields,
$info[$i][$j][0]);
I hope this gets you started.