What are the potential security risks associated with implementing LDAP authentication in PHP?

Potential security risks associated with implementing LDAP authentication in PHP include the risk of LDAP injection attacks, where attackers can manipulate LDAP queries to gain unauthorized access to the system. To mitigate this risk, it is crucial to properly sanitize user input before constructing LDAP queries.

// Sanitize user input before constructing LDAP query
$username = ldap_escape($_POST['username']);
$password = ldap_escape($_POST['password']);

// LDAP authentication code
$ldapconn = ldap_connect("ldap.example.com");
if ($ldapconn) {
    $ldapbind = ldap_bind($ldapconn, "cn=$username,dc=example,dc=com", $password);

    if ($ldapbind) {
        echo "LDAP bind successful!";
    } else {
        echo "LDAP bind failed";
    }
} else {
    echo "Unable to connect to LDAP server";
}