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

When handling user input in PHP forms, it is crucial to validate and sanitize the input to prevent vulnerabilities such as SQL injection or cross-site scripting attacks. One best practice is to always use prepared statements when interacting with a database to prevent SQL injection. Additionally, input validation should be performed to ensure that the data meets the expected format and type.

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

// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare('INSERT INTO users (username, email) VALUES (:username, :email)');
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();