What are the best practices for handling form data printing in PHP projects?

When handling form data in PHP projects, it is important to properly sanitize and validate the input before printing it to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. One way to do this is by using PHP's htmlspecialchars() function to encode special characters in the input data before displaying it on the page.

<?php
// Get form data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);

// Print sanitized form data
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
?>