What are the potential risks of not escaping output when displaying data in PHP?

Not escaping output when displaying data in PHP can leave your application vulnerable to Cross-Site Scripting (XSS) attacks, where malicious scripts can be injected into your page and executed in the context of your site. To prevent this, always escape output using functions like htmlspecialchars() before displaying any user-generated content on your website.

<?php
// Unsafe output without escaping
$userInput = "<script>alert('XSS attack!');</script>";
echo $userInput; // This will execute the script

// Safe output with escaping
$userInput = "<script>alert('XSS attack!');</script>";
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8'); // This will display the script as text
?>