What are some best practices for handling form data in PHP to avoid displaying unwanted values?

When handling form data in PHP, it is important to sanitize and validate the input to avoid displaying unwanted values. One way to achieve this is by using PHP's filter_input function to filter and validate the input data. Additionally, you can use htmlentities function to escape any special characters in the input data to prevent XSS attacks.

// Sanitize and validate form data
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

// Escape special characters
$name = htmlentities($name);
$email = htmlentities($email);