What best practices should be followed when validating user input in PHP scripts to prevent errors and vulnerabilities?

When validating user input in PHP scripts, it is essential to sanitize and validate the data to prevent errors and vulnerabilities such as SQL injection and cross-site scripting attacks. One common practice is to use PHP's filter_input function along with appropriate filter flags to validate input data.

// Example of validating user input in PHP script
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

if(!$username || !$email){
    // Handle validation errors
    echo "Invalid input data";
} else {
    // Proceed with safe data
    // Perform further processing
}