What are the best practices for handling user input, especially when dealing with sensitive information like CAPTCHA codes?

When handling user input, especially sensitive information like CAPTCHA codes, it is crucial to sanitize and validate the input to prevent malicious attacks or errors. One way to achieve this is by using PHP's filter_input function with FILTER_SANITIZE_STRING and FILTER_VALIDATE_STRING filters to clean and validate the input before processing it further.

$captcha_code = filter_input(INPUT_POST, 'captcha_code', FILTER_SANITIZE_STRING);

if (filter_var($captcha_code, FILTER_VALIDATE_STRING)) {
    // Process the CAPTCHA code
} else {
    // Handle invalid input
}