Security Resources

OWASP Cheat Sheet: Cross-Site Scripting Prevention

Learn context-aware output encoding and other defensive practices for preventing cross-site scripting in web applications.

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.

Official resource

OWASP XSS Prevention Cheat Sheet

Share this page Help other developers discover this resource.