Connect to an LDAP server with PHP
Posted by Jon on September 22nd, 2011

This is just a small function that I wrote to connect to an LDAP server.  It will connect to one server but will take multiple domains within that server as arguments.  It parses the results and outputs three very common fields (firstname, lastname, and email address).  The code is pretty well documented, so I’ll just leave it at that.

  1. <?php
  2. /**
  3.  * Merge data from an LDAP search from multiple domains into a single array
  4.  *
  5.  * Connect to a single LDAP server and supply one or multiple domains to search and
  6.  * this function will loop through each domain adding a new entry to the array for each
  7.  * new element provided in LDAP. Currently it only provides the firstname, lastname,
  8.  * and email as outputs.
  9.  *
  10.  * @access public
  11.  *
  12.  * @param string $ldapserver e.g. 10.12.12.234
  13.  * @param string $user e.g. uid=username
  14.  * @param string $pass e.g. [email protected]
  15.  * @param array $ldapdn e.g. array( "dc=example,dc=com" )
  16.  * @param string $search e.g sn=*\
  17.  *
  18.  * @return array $details = array ( 0 => array ( "firstname" => "joe",
  19.  * "lastname" => "sands", "email" => "[email protected]" ) )
  20.  *
  21.  */
  22.  
  23. function mergeLdapDn( $ldapserver = "", $user = "", $pass = "", $ldapdn = array(), $search = "" ) {
  24.  
  25. // basic sequence with LDAP is connect, bind, search, interpret search result, close connection
  26.  
  27. // connect to ldap server
  28. $ldapconn = ldap_connect($ldapserver)
  29. or die("Could not connect to LDAP server.");
  30.  
  31. // Set some ldap options for talking to
  32. ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
  33. ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
  34.  
  35. if ($ldapconn) :
  36. ldap_bind($ldapconn, $user, $pass);
  37. // Loop through each of the dn-s supplied in the function
  38. foreach ( $ldapdn as $dn ) :
  39. // Search surname entry
  40. $sr=ldap_search($ldapconn, $dn, $search);
  41. $entries = ldap_get_entries($ldapconn, $sr);
  42. // Loop through the result set keeping only the necessary info
  43. foreach ( $entries as $entry ) :
  44. // Throw out the entry if there is no first name listed
  45. if(isset($entry["givenname"])) :
  46. $details[] = array(
  47. "firstname" => $entry["givenname"][0],
  48. "lastname" => $entry["sn"][0],
  49. "email" => $entry["mail"][0]
  50. );
  51. endif;
  52. endforeach;
  53. endforeach;
  54. ldap_close($ldapconn);
  55. return $details;
  56. else :
  57. return false;
  58. endif;
  59. }
  60. ?>

Leave Your Response

* Name, Email, Comment are Required