What are best practices for handling authentication methods in PHP when working with LDAP servers?

When working with LDAP servers for authentication in PHP, it is important to securely handle user credentials to prevent unauthorized access. One best practice is to use secure protocols like LDAPS (LDAP over SSL) for communication. Additionally, it is recommended to hash passwords before sending them to the LDAP server and to properly sanitize input to prevent LDAP injection attacks.

// Example of securely authenticating user with LDAP server using LDAPS

$ldap_server = 'ldaps://ldap.example.com';
$ldap_port = 636;
$ldap_dn = 'cn=admin,dc=example,dc=com';
$ldap_password = 'admin_password';

$ldap_conn = ldap_connect($ldap_server, $ldap_port);
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);

if (ldap_bind($ldap_conn, $ldap_dn, $ldap_password)) {
    echo 'Authentication successful';
} else {
    echo 'Authentication failed';
}

ldap_close($ldap_conn);