What are some recommended ways to sanitize and validate user input in PHP forms to prevent errors and vulnerabilities?

To sanitize and validate user input in PHP forms, it is important to use functions like htmlentities() or htmlspecialchars() to prevent XSS attacks by converting special characters to HTML entities. Additionally, you can use functions like filter_var() with appropriate filters to validate input data such as email addresses or URLs. It's also recommended to use prepared statements when interacting with a database to prevent SQL injection attacks.

// Sanitize user input using htmlentities()
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);

// Validate email input using filter_var()
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Email is valid
} else {
    // Email is not valid
}

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