Glossary · Security & Resilience

What is XSS (cross-site scripting)?

Short answer

XSS (cross-site scripting) is a security vulnerability where an attacker gets their own JavaScript to run in other users’ browsers on a trusted website, typically by submitting input that the site later displays without proper escaping. The script can then steal session data, act as the user or change what the page shows.

The three kinds

  • Stored: malicious input is saved (a comment, a profile name) and shown to every visitor. The most damaging.
  • Reflected: the input comes from the request, such as a search term in the URL, and is echoed straight back.
  • DOM-based: front-end JavaScript writes untrusted data into the page, for example with innerHTML.

How to prevent it

  • Escape output by default: Blade’s {{ }} and Twig escape automatically. Be very careful with {!! !!}, |raw and plain echo; in plain PHP use htmlspecialchars($value, ENT_QUOTES, 'UTF-8').
  • Escape for the context: HTML text, HTML attributes, JavaScript, CSS and URLs each need different encoding. Don’t place user input inside <script> blocks.
  • Sanitise rich text with an allow-list library such as HTML Purifier or Symfony’s HTML Sanitizer when users may submit HTML.
  • Set a Content Security Policy that blocks inline scripts, so injected code can’t run even if escaping fails.
  • Use HttpOnly cookies for sessions so scripts can’t read them.

AI features add a new path: model output displayed as HTML can carry injected markup, so escape it like any user input.

Published · Updated · By · All terms

Go deeper