Application Security

Prevent Cross-Site Scripting (XSS) in PHP

Understand reflected, stored, and DOM-based XSS and use context-appropriate output encoding in PHP templates.

Escape dynamic HTML text

function e(string $value): string
{
    return htmlspecialchars(
        $value,
        ENT_QUOTES | ENT_SUBSTITUTE,
        'UTF-8'
    );
}

echo '<p>' . e($comment) . '</p>';

Escape untrusted values when rendering them. Input validation alone does not make content safe for HTML output.

Understand output context

HTML text, attributes, JavaScript, CSS, and URLs have different rules. Prefer avoiding inline JavaScript and never build executable script from user input.

For URL query values, use rawurlencode() or http_build_query() as appropriate. Validate allowed URL schemes.

Allow rich HTML carefully

If users may submit formatted HTML, use a maintained sanitizer with a strict allowlist. htmlspecialchars() is appropriate when content should be displayed as text.

Add browser defenses

A carefully configured Content Security Policy can reduce the impact of some XSS flaws, but it does not replace correct output encoding.