What are the best practices for handling HTML input in PHP to prevent JavaScript injection?

To prevent JavaScript injection when handling HTML input in PHP, it is important to sanitize and validate the input data. One common approach is to use the htmlspecialchars function to convert special characters into their HTML entities, preventing any potential JavaScript code from being executed.

// Sanitize HTML input to prevent JavaScript injection
$input = "<script>alert('Hello, world!');</script>";
$sanitized_input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');

echo $sanitized_input;