How does the ldap_search function work in PHP when trying to retrieve information from Active Directory?

When using the ldap_search function in PHP to retrieve information from Active Directory, you need to provide the LDAP connection resource, the base DN (Distinguished Name) where the search should start, the search filter, and an array of attributes to retrieve. Make sure to bind to the LDAP server before performing the search and handle any errors that may occur during the process.

// LDAP server settings
$ldapServer = 'ldap://your_ldap_server';
$ldapUser = 'username';
$ldapPass = 'password';

// Connect to LDAP server
$ldapConn = ldap_connect($ldapServer);
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);

// Bind to LDAP server
$ldapBind = ldap_bind($ldapConn, $ldapUser, $ldapPass);

// Search for information in Active Directory
$baseDN = 'dc=example,dc=com';
$filter = '(objectClass=user)';
$attributes = array('cn', 'mail', 'telephoneNumber');
$search = ldap_search($ldapConn, $baseDN, $filter, $attributes);
$info = ldap_get_entries($ldapConn, $search);

// Close LDAP connection
ldap_close($ldapConn);