What are some best practices for handling form input validation in PHP functions?

When handling form input validation in PHP functions, it is important to sanitize and validate user input to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. One best practice is to use PHP's filter_input function along with filter_var to validate input data. Additionally, it is recommended to use regular expressions to enforce specific input formats.

// Example of handling form input validation in a PHP function

function validateInput($input) {
    // Sanitize the input data
    $sanitizedInput = filter_var($input, FILTER_SANITIZE_STRING);

    // Validate the input data using regular expressions
    if (preg_match("/^[a-zA-Z0-9]+$/", $sanitizedInput)) {
        return true; // Input is valid
    } else {
        return false; // Input is invalid
    }
}

// Example usage
$input = $_POST['input_field'];
if (validateInput($input)) {
    // Input is valid, proceed with further processing
} else {
    // Input is invalid, display an error message to the user
}