What are the best practices for handling form submissions in PHP to prevent cross-site scripting vulnerabilities?

To prevent cross-site scripting vulnerabilities when handling form submissions in PHP, it is important to sanitize and validate user input before processing it. This can be done by using functions like htmlspecialchars() to escape special characters and prevent malicious scripts from being executed. Additionally, using prepared statements when interacting with a database can help prevent SQL injection attacks.

// Sanitize and validate user input before processing
$name = htmlspecialchars($_POST['name']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

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