How can the htmlspecialchars() function be used to prevent HTML injection in PHP scripts?

HTML injection occurs when user input containing HTML tags is not properly sanitized before being displayed on a webpage, allowing malicious code to be executed. To prevent this, the htmlspecialchars() function can be used in PHP scripts to convert special characters like < and > into their HTML entity equivalents, rendering them harmless. This ensures that user input is displayed as plain text rather than being interpreted as HTML code.

// Example of using htmlspecialchars() to prevent HTML injection
$user_input = &quot;&lt;script&gt;alert(&#039;Hello!&#039;);&lt;/script&gt;&quot;;
$safe_input = htmlspecialchars($user_input);
echo $safe_input;