How does htmlentities() help in preventing users from injecting malicious HTML or JavaScript code on a webpage in PHP?

The htmlentities() function in PHP helps prevent users from injecting malicious HTML or JavaScript code on a webpage by converting special characters to their HTML entities. This means that any code entered by the user will be displayed as plain text on the webpage, preventing it from being executed as code.

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