What are some best practices for preventing XSS attacks in PHP, particularly when handling user input?
XSS attacks can be prevented in PHP by properly sanitizing and escaping user input before displaying it on a web page. One common way to do this is by using the htmlspecialchars() function to convert special characters into HTML entities, ensuring that any malicious scripts are not executed.
$user_input = "<script>alert('XSS attack!');</script>";
$clean_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $clean_input;