What are some common methods to prevent XSS security vulnerabilities in PHP code?

One common method to prevent XSS security vulnerabilities in PHP code is to sanitize user input before displaying it on a webpage. This involves using functions like htmlspecialchars() or htmlentities() to escape special characters that could be interpreted as HTML or JavaScript code. Additionally, using prepared statements with PDO or mysqli when interacting with a database can help prevent SQL injection attacks, which can also lead to XSS vulnerabilities.

// Sanitize user input before displaying it on a webpage
$user_input = "<script>alert('XSS attack!')</script>";
$sanitized_input = htmlspecialchars($user_input);
echo $sanitized_input;