What general best practice should be followed when handling user input in PHP to prevent potential XSS attacks?
To prevent potential XSS attacks when handling user input in PHP, it is essential to sanitize and validate all user input before displaying it on a webpage. This can be achieved by using functions like htmlentities() or htmlspecialchars() to encode special characters in the input data. Additionally, it is recommended to use prepared statements when interacting with a database to prevent SQL injection attacks.
// Sanitize user input to prevent XSS attacks
$input = "<script>alert('XSS attack!');</script>";
$sanitized_input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
echo $sanitized_input;