How can data validation and sanitation be improved in the PHP code provided to prevent potential security vulnerabilities?

To improve data validation and sanitation in PHP code, you can use functions like filter_var() to validate input data and htmlentities() to sanitize output data. By validating input data, you can ensure that only expected data types are accepted, reducing the risk of injection attacks. Sanitizing output data helps prevent XSS attacks by escaping special characters.

// Validate input data using filter_var()
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

// Sanitize output data using htmlentities()
echo htmlentities($userInput, ENT_QUOTES, 'UTF-8');