What best practices should be followed when handling search results from Active Directory in PHP using LDAP functions?

When handling search results from Active Directory in PHP using LDAP functions, it is important to properly handle errors, sanitize input to prevent LDAP injection attacks, and securely bind to the LDAP server. Additionally, it is recommended to use pagination when retrieving large result sets to improve performance and avoid timeouts.

// Connect to LDAP server
$ldapconn = ldap_connect("ldap://example.com");

// Bind to LDAP server securely
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
$ldapbind = ldap_bind($ldapconn, "username@example.com", "password");

// Search for entries in Active Directory
$ldapsearch = ldap_search($ldapconn, "ou=Users,dc=example,dc=com", "(cn=John Doe)");
$ldapentries = ldap_get_entries($ldapconn, $ldapsearch);

// Loop through search results
foreach ($ldapentries as $entry) {
    // Process each entry
}

// Close LDAP connection
ldap_close($ldapconn);