PHP 8 interview question · Most asked

How do you prevent XSS in PHP applications?

Summary

Escape output for its context: htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') for HTML, json_encode with hex flags for JS, rawurlencode for URLs. Add a Content-Security-Policy as defense in depth.

Longer Answer

XSS is an output problem: you escape at render time based on where data lands. Templating engines (Twig, Blade {{ }}) auto-escape HTML by default; raw output ({!! !!}, |raw) must be reserved for sanitized HTML (use HTML Purifier for user-supplied rich text). Set cookies HttpOnly so scripts can't read session IDs.

Code Example

<?php
function e(?string $value): string
{
    return htmlspecialchars($value ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>
<p>Hello, <?= e($user->name) ?></p>
<script>const user = <?= json_encode($user, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;</script>

Key Points

  • Escape on output, per context
  • Use auto-escaping templates
  • Sanitize rich HTML with HTML Purifier
  • CSP and HttpOnly cookies limit impact

More most-asked PHP 8 questions

← All PHP 8 questions