Cross-site scripting (XSS) happens when untrusted data is interpreted as executable content in a user's browser. It can affect content systems, search pages, profile fields, administrative interfaces and any feature that displays user-controlled values.
Encode at the output context
For HTML text and quoted attributes, use context-appropriate encoding such as PHP's htmlspecialchars with quotes and UTF-8 handling. JavaScript, CSS, URL and HTML contexts have different parsing rules; HTML encoding is not a universal sanitizer. Avoid inserting untrusted strings into script blocks or event-handler attributes.
Treat rich text separately
If users are allowed to author HTML, use a maintained HTML sanitizer with an explicit allowlist of elements and attributes. Do not attempt to sanitize HTML with regular expressions. Store the content model clearly and encode ordinary text when rendering it.
Reduce dangerous DOM sinks
On the frontend, prefer textContent over innerHTML for plain text. If HTML insertion is required, sanitize with a suitable library and keep the trusted/untrusted boundary visible in code review. Validate URLs before placing them in navigation or resource attributes.
Add defense in depth
A Content Security Policy can reduce the impact of some injection flaws, but it does not replace output encoding. Keep dependencies updated and test stored and reflected input paths, including administrative screens.
Checklist
- Encode data at the point of output for its context.
- Sanitize intentionally permitted rich HTML with an allowlist.
- Prefer safe DOM APIs for plain text.
- Validate untrusted URLs.
- Use CSP as an additional layer, not the primary fix.