What role does htmlentities() and htmlspecialchars() play in preventing code injection in PHP applications?

htmlentities() and htmlspecialchars() are PHP functions used to convert special characters in a string to their HTML entity equivalents. This helps prevent code injection attacks by encoding characters that could potentially be used to execute malicious code. By using these functions, any user input displayed on a webpage will be rendered as plain text rather than interpreted as HTML or JavaScript code.

$user_input = "<script>alert('Hello!');</script>";
$encoded_input = htmlentities($user_input);
echo $encoded_input;