Field Manual PHP / Laravel reference
← Security

Cross-site scripting (XSS)

XSS lets attacker-controlled text execute as script in a browser.

What it is

XSS lets attacker-controlled text execute as script in a browser.

When to use it

Encode at the output context; render untrusted content as text.

Syntax

{{-- Bad for untrusted content: {!! $comment !!} --}}
{{-- Good: --}}
{{ $comment }}

Example

// PHP HTML text context:
echo htmlspecialchars($comment, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
// JavaScript DOM:
// element.textContent = untrustedText;

Common mistakes

HTML escaping is not universal encoding for URLs/JS/CSS; rich HTML needs a trusted sanitizer.

Related topics

Browse Security