What are the best practices for connecting to an LDAP server in PHP and handling authentication to retrieve data efficiently?

When connecting to an LDAP server in PHP and handling authentication, it's important to use secure connection methods, properly escape user input to prevent injection attacks, and efficiently retrieve data by using filters and limiting the attributes returned.

// Connect to LDAP server with secure connection
$ldapServer = 'ldaps://ldap.example.com';
$ldapPort = 636;
$ldapConn = ldap_connect($ldapServer, $ldapPort);
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);

// Bind with a service account for authentication
$ldapBindUser = 'cn=admin,dc=example,dc=com';
$ldapBindPass = 'password';
ldap_bind($ldapConn, $ldapBindUser, $ldapBindPass);

// Search for a user by username
$username = 'john.doe';
$filter = "(uid=$username)";
$attributes = array("cn", "mail");
$result = ldap_search($ldapConn, "ou=users,dc=example,dc=com", $filter, $attributes);
$entries = ldap_get_entries($ldapConn, $result);

// Retrieve user data
if ($entries['count'] > 0) {
    $user = $entries[0];
    echo "Username: " . $user['cn'][0] . "<br>";
    echo "Email: " . $user['mail'][0] . "<br>";
}

// Close LDAP connection
ldap_unbind($ldapConn);