Overview
Cross-site scripting (XSS) occurs when untrusted data is interpreted as executable content in a user's browser. PHP applications can be exposed when request data, database content or third-party values are inserted into HTML without appropriate handling.
Context matters
HTML text, HTML attributes, JavaScript, CSS and URL contexts require different defenses. In PHP, htmlspecialchars() is commonly used for HTML text and attribute output with appropriate flags and encoding, but it is not a universal encoder for every context.
Practical defenses
Prefer safe templating patterns, avoid constructing script code from untrusted strings, validate URL schemes before placing URLs into links and use a Content Security Policy as an additional layer. Keep input validation and output encoding as separate responsibilities.
Test carefully
Review every place untrusted data reaches a browser, including admin interfaces and stored content. Test encoded and malformed values in the context where they are rendered.