What are the best practices for handling user input validation in PHP to prevent errors like "500 Error" responses?

When handling user input validation in PHP, it is crucial to sanitize and validate all input data to prevent errors like "500 Error" responses. To achieve this, use PHP functions like filter_input() or filter_var() to sanitize and validate user input before processing it in your application.

// Example of handling user input validation in PHP to prevent errors like "500 Error" responses

// Retrieve and sanitize user input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);

// Validate the input data
if (empty($username) || empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Handle validation errors
    echo "Invalid input data";
} else {
    // Process the input data
    // Your code here
}