What are the potential pitfalls of not properly escaping characters in PHP when outputting data?

Not properly escaping characters in PHP when outputting data can lead to security vulnerabilities such as cross-site scripting (XSS) attacks, where malicious scripts can be injected into the webpage. To prevent this, always use functions like htmlspecialchars() or htmlentities() to escape special characters before outputting user input or dynamic data on a webpage.

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

// Properly escape characters before output
$userInput = "<script>alert('XSS attack')</script>";
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
?>