PHP Security

Preventing Cross-Site Scripting in PHP Applications

Learn how output escaping, context-aware encoding, and safe templates help prevent cross-site scripting vulnerabilities.

Preventing Cross-Site Scripting in PHP Applications

Cross-site scripting (XSS) happens when an application includes untrusted data in a page in a way that lets it run as browser code. Attackers may use XSS to manipulate page content or perform actions as a visitor.

Escape Output for HTML

When displaying plain text inside HTML, use htmlspecialchars() with quotes and UTF-8 handling.

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

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

Escaping should happen when output is rendered, not by permanently modifying the stored value.

Validate Input, but Do Not Rely on Validation Alone

Input validation checks whether data matches the application's expected format. It is useful for business rules, but it does not replace output encoding. A value that is valid in one context may still be unsafe in another.

Different Output Contexts Need Different Handling

HTML text, HTML attributes, URLs, JavaScript, and CSS have different parsing rules. Use context-appropriate encoding and avoid inserting untrusted values into inline scripts or style blocks. Prefer safe DOM APIs and external JavaScript files.

Allow Rich HTML Carefully

If users are allowed to submit formatted HTML, do not simply print it after calling htmlspecialchars() or trust it because it came from an editor. Use a maintained HTML sanitizer with a strict allowlist of permitted elements and attributes.

Additional Defenses

Use a Content Security Policy as an additional layer, keep dependencies updated, and test templates with hostile input. A CSP does not replace correct output encoding.

Conclusion

The most reliable everyday XSS defense is context-aware output encoding. In PHP templates, escape untrusted text by default and allow rich HTML only through a carefully maintained sanitization process.

Share this page Help other developers discover this resource.