What are best practices for handling user input in PHP forms for LDAP authentication?

When handling user input in PHP forms for LDAP authentication, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or LDAP injection attacks. One way to achieve this is by using PHP's filter_input() function with FILTER_SANITIZE_STRING filter to sanitize the input data.

$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

// LDAP authentication code
$ldap_server = "ldap.example.com";
$ldap_port = 389;
$ldap_base_dn = "dc=example,dc=com";

$ldap_connection = ldap_connect($ldap_server, $ldap_port);
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);

if (ldap_bind($ldap_connection, "cn=$username,$ldap_base_dn", $password)) {
    echo "LDAP authentication successful";
} else {
    echo "LDAP authentication failed";
}

ldap_close($ldap_connection);