What are the best practices for handling user input data in PHP forms to prevent errors and vulnerabilities?

When handling user input data in PHP forms, it is important to sanitize and validate the data to prevent errors and vulnerabilities such as SQL injection and cross-site scripting attacks. One way to do this is by using PHP functions like htmlspecialchars() to sanitize user input and filter_var() to validate input against specific rules.

// Sanitize user input data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);

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