What best practices should be followed when handling user input in PHP to prevent errors?

When handling user input in PHP, it is important to validate and sanitize the data to prevent errors and vulnerabilities such as SQL injection and cross-site scripting attacks. One common best practice is to use PHP's filter_input function to validate user input against a specified filter type. Additionally, always use prepared statements when interacting with a database to prevent SQL injection attacks.

// Validate and sanitize user input using filter_input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

// Use prepared statements to interact with the database
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();