What are the potential security risks associated with not properly handling context changes in PHP, especially in relation to HTML output?

Improper handling of context changes in PHP can lead to security risks such as cross-site scripting (XSS) attacks, where an attacker injects malicious scripts into the HTML output. To mitigate this risk, it is crucial to properly escape and sanitize user input before outputting it to the HTML context. This can be achieved using functions like htmlspecialchars() to encode special characters and prevent script injection.

// Example of properly handling context changes in PHP to prevent XSS attacks
$user_input = "<script>alert('XSS attack!')</script>";
$safe_output = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $safe_output;