What are the best practices for filtering POST data in PHP before using it in the code?

When receiving POST data in PHP, it is essential to filter and sanitize the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One common approach is to use the filter_input() function along with specific filter types to validate and sanitize the input data before using it in the code.

// Example of filtering POST data in PHP
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

// Using the filtered data in the code
if ($username && $email) {
    // Process the data securely
    echo "Username: " . $username . "<br>";
    echo "Email: " . $email;
} else {
    // Handle invalid input
    echo "Invalid input data";
}