Skip to content
PHP Logo

How can PHP developers prevent XSS attacks when displaying user input in HTML?

To prevent XSS attacks when displaying user input in HTML, PHP developers can use the `htmlspecialchars` function to encode the user input before outputting it to the page. This function will convert special characters like < and > into their HTML entities, preventing them from being interpreted as code by the browser.

php
$userInput = $_POST['user_input']; // Assuming user input is retrieved from a form submission
$encodedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo $encodedInput;