What potential security risks are present in directly inserting variables into HTML code in PHP?

Directly inserting variables into HTML code in PHP can lead to security risks such as cross-site scripting (XSS) attacks if the variables are not properly sanitized. To mitigate this risk, it is important to properly escape the variables before inserting them into the HTML code. This can be done using functions like htmlspecialchars() or htmlentities() to convert special characters to their HTML entities.

<?php
// Unsafe way of inserting variable into HTML code
$unsafe_variable = $_GET['user_input'];
echo "<p>$unsafe_variable</p>";

// Safe way of inserting variable into HTML code
$safe_variable = htmlentities($_GET['user_input']);
echo "<p>$safe_variable</p>";
?>