Skip to content
PHP Logo

How can XSS attacks be prevented when passing variables from PHP to HTML?

XSS attacks can be prevented when passing variables from PHP to HTML by properly escaping the output using htmlentities() or htmlspecialchars() functions. These functions will convert special characters in the variable to their HTML entities, making it safe to display in the HTML document.

php
<?php
// Example variable containing user input
$user_input = "<script>alert('XSS attack!');</script>";

// Escaping the user input before outputting it to HTML
echo htmlentities($user_input);
?>