How can PHP developers securely handle user authentication and authorization against an LDAP server?

PHP developers can securely handle user authentication and authorization against an LDAP server by using the LDAP extension in PHP to connect to the LDAP server, bind with a service account, search for the user's DN based on their username, and then attempt to bind with the user's DN and password to authenticate them. It's important to properly escape user input to prevent LDAP injection attacks and to use secure connection methods like LDAPS to encrypt the communication with the LDAP server.

<?php

$ldapServer = 'ldap.example.com';
$ldapPort = 389;
$ldapBaseDn = 'dc=example,dc=com';
$ldapUsername = 'cn=admin,dc=example,dc=com';
$ldapPassword = 'admin_password';

$ldapConn = ldap_connect($ldapServer, $ldapPort);
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);

if (ldap_bind($ldapConn, $ldapUsername, $ldapPassword)) {
    $searchResult = ldap_search($ldapConn, $ldapBaseDn, "(uid=user123)");
    $entries = ldap_get_entries($ldapConn, $searchResult);

    if ($entries['count'] > 0) {
        $userDn = $entries[0]['dn'];
        if (ldap_bind($ldapConn, $userDn, 'user123_password')) {
            echo "User authenticated successfully!";
        } else {
            echo "Invalid credentials.";
        }
    } else {
        echo "User not found.";
    }
} else {
    echo "Failed to bind to LDAP server.";
}

ldap_close($ldapConn);

?>