PHP Reference ยท Web and Security
XSS prevention in PHP
Prevent cross-site scripting in PHP: escape output with htmlspecialchars() for each context (HTML, attributes, URLs, JavaScript), and add a Content-Security-Policy.
Cross-site scripting (XSS) happens when an attacker's text is placed into your page and the browser runs it as code. A comment containing <script> that you print unchanged will run in every visitor's browser, with access to their session and everything on the page.
The cure is escaping: convert characters that have a special meaning into harmless text at the moment you print them. In PHP that is htmlspecialchars() for HTML. The rule is "escape on output, for the context you are writing into": the right escaping depends on where the value lands.
echo htmlspecialchars($comment, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Context matters
| Where the value is printed | What to do |
|---|---|
| HTML text or attribute value | htmlspecialchars($v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'). Always quote attributes. |
| URL query value | urlencode() or rawurlencode(), then HTML-escape the whole URL. |
URL as href or src |
Allow only http, https (and mailto: if needed); never print javascript: or data: URLs from users. |
Inside <script> |
Print data with json_encode() and the JSON_HEX_* flags. Never build code by concatenating strings. |
| Inside CSS or event-handler attributes | Avoid; move the value into a data attribute and read it with JavaScript. |
| Rich HTML (a blog editor) | Use a maintained sanitizer such as HTMLPurifier. strip_tags() is not safe. |
Usage notes
- Escape on output, not on input. Stored data should stay faithful; escape when you know the destination. Template engines (Blade, Twig) escape by default: use the raw-output syntax only for trusted HTML.
- Always pass
ENT_QUOTESandUTF-8. Since PHP 8.1 the default flags include both quotes and substitution, but spelling them out makes intent clear and works on older versions. - Never use
strip_tags()oraddslashes()as XSS defenses. They do not cover every context. - Validation is not escaping. Checking that input "looks like a name" helps, but escape anyway.
- Content-Security-Policy (a response header) limits which scripts may run and softens the impact of a mistake. See
header(). - Cookies: set
HttpOnlyso scripts cannot read the session cookie; seesetcookie(). - XSS also defeats CSRF tokens, so fix it first. See CSRF protection.