What are the best practices for input validation and sanitization when handling user-submitted data in a PHP application to prevent security vulnerabilities?

Input validation and sanitization are crucial steps in preventing security vulnerabilities in PHP applications. To ensure the data submitted by users is safe, it is important to validate input against expected formats and sanitize it to remove potentially harmful content such as SQL injection or cross-site scripting (XSS) attacks. Here is a simple example of how you can validate and sanitize user input in a PHP application using the filter_var() function:

// Validate and sanitize user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

// Check if the input is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Invalid email address
    echo "Invalid email address";
} else {
    // Process the data
    // ...
}