What are the advantages of using filter_input() function in PHP for validating and filtering form data inputs?

When working with form data inputs in PHP, it is crucial to validate and filter the data to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. The filter_input() function in PHP provides a convenient way to validate and filter user inputs based on predefined filters such as validating email addresses, URLs, and numbers. This function helps ensure that the data being passed into your application is safe and meets the expected format.

// Example of using filter_input() function to validate and filter form data inputs
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT);

if($username && $email && $age) {
    // Data is valid, proceed with processing
} else {
    // Data is invalid, handle error accordingly
}