Engineering 5 min read Updated
Escaping output so that XSS cannot run
In short
Escape each value for the place where it is printed, because text that is safe in HTML can still run as code inside a script, a URL or CSS.
Cross-site scripting (XSS) happens when text from a user, a database or another system reaches a page as code that the browser runs. Escaping prevents this by changing the characters that have a special meaning where the text is printed. Choose the encoder by the place the value lands, not one encoder for everything.
Encode for the context, not once
The OWASP XSS Prevention Cheat Sheet starts from a simple rule: the encoding depends on where the value lands. Text between HTML tags, text inside an attribute, a JavaScript string, a URL and a CSS declaration are different places. A value that is safe in one of them can be dangerous in another.
For ordinary HTML body text, the cheat sheet gives these replacements:
| Character | Replacement |
|---|---|
| & | & |
| < | < |
| > | > |
| " | " |
| ' | ' |
In JavaScript, assign untrusted text to the textContent property of an ordinary element, and do not encode it beforehand. Assigning the same text to innerHTML lets the browser parse it as markup.
For attributes, always quote the value. Avoid inline event-handler attributes such as onclick. OWASP prefers addEventListener with trusted handler functions, because attribute encoding does not protect JavaScript inside an event-handler attribute. Do not pre-encode values that you pass to setAttribute.
Scripts, URLs and CSS need their own rules
Each of the other contexts has its own rules in the cheat sheet:
- Inline scripts. Never insert untrusted code, identifiers or expressions. Manual quote escaping is fragile, so use an encoder documented for both the JavaScript string and the enclosing HTML script.
- URLs. Percent-encode parameter values. In JavaScript, apply encodeURIComponent to each untrusted query parameter. For href and src, apply URL encoding first and then HTML attribute encoding.
- CSS. Do not place untrusted data in CSS source, including selectors and property names. For dynamic styling, use element.style.setProperty with a fixed property name and an allowlist for the value. Properties that load resources, such as background-image, need separate URL validation.
Check what happens to a value after encoding, because eval() and similar functions run code.
What htmlspecialchars does by default
The PHP manual gives htmlspecialchars the default flags ENT_QUOTES, ENT_SUBSTITUTE and ENT_HTML401. Since PHP 8.1.0 the default has been this combination; before that, the flags default was ENT_COMPAT. With ENT_QUOTES, both double and single quotes are converted, and in the HTML 401 document type a single quote becomes '. If you pass your own flags, they replace the defaults. The encoding argument falls back to the default_charset setting, and the manual encourages setting it explicitly.
| Flag | Effect according to the manual |
|---|---|
| ENT_QUOTES | Converts both double and single quotes. |
| ENT_COMPAT | Converts double quotes and leaves single quotes alone. |
The function is designed for text and attribute values in HTML. It does not make a value safe inside a script block or inside a URL, where the rules above apply. Pass the flags and the encoding explicitly, so that the result does not depend on the PHP version or the server configuration.
This article summarises the OWASP cheat sheet and the PHP manual for orientation. It is not a security audit. Check the current versions of the sources and test your own templates.
Working on something similar in your own product? A few honest sentences are enough – we read every enquiry and reply by email. Apply with your idea
When users must write HTML
Sometimes a user needs to write formatting, for example in a comment field with a rich-text editor. Output encoding would then show the markup as plain text, so the cheat sheet recommends HTML sanitisation instead, and it names DOMPurify for that job. Do not change the sanitised content afterwards, confirm that later libraries leave it intact, and patch the sanitiser regularly.
Content Security Policy as a second layer
A Content Security Policy (CSP) limits which scripts a browser will run. OWASP treats it as defence in depth and recommends a policy written for each application, not one blanket policy for a whole organisation. It also warns that implementation mistakes are easy to make, so CSP should never be your primary defence. For the header itself, read the article on Content Security Policy.
Checklist before release
Use this list on every template that prints data from users:
- Find every place where stored or user-supplied text is printed, and note its context: HTML text, attribute, script, URL or CSS.
- Choose the encoder for that context. In PHP, pass the flags and the encoding explicitly.
- Replace inline event-handler attributes with addEventListener, and use textContent instead of innerHTML for untrusted text.
- If users write HTML, sanitise it with a maintained library, keep that library patched, and do not change its output afterwards.
- Add a Content Security Policy as an extra layer and check that it does not break the page. Review the response headers as described in the article on HTTP security headers.
- Check uploaded files and their names before showing them, as covered in the article on accepting file uploads safely.
Common questions
- Is htmlspecialchars enough to stop XSS?
- It suits text and attribute values in HTML, but it does not make a value safe inside a script block, a URL or CSS. Those contexts need their own rules, which the OWASP cheat sheet describes.
- Why do the default flags of htmlspecialchars matter?
- Since PHP 8.1.0 the default flags convert both double and single quotes. Passing your own flags replaces the defaults, so set the flags and the encoding explicitly.
- Can a Content Security Policy replace escaping?
- No. OWASP treats CSP as defence in depth and warns that its implementation is easy to get wrong, so it should not be the primary defence.
Sources
- Cross Site Scripting Prevention Cheat Sheet, OWASP Cheat Sheet Series. Accessed 24 November 2026
- htmlspecialchars, PHP Documentation Group (php.net). Accessed 24 November 2026
Further reading
-
A Content Security Policy that holds in practice
A policy holds when inline scripts are gone, every nonce is fresh on each response, and the rules have been tested in report-only mode first.
-
Preventing SQL injection with prepared statements
Send every user-supplied value to the database as a bound parameter, take table names and sort orders from fixed lists, and give the application only the rights it needs.
-
Accepting file uploads safely in PHP
Check every upload on the server, accept only the file types the application needs, and store the file where no visitor can run it or fetch it directly.
Have an idea that should exist? Or a working product that needs more customers, a new website or a complete rework? Bring us anything. Apply with your idea