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
HttpOnlycookies limit impact
More most-asked PHP 8 questions
- What are the most important features introduced in PHP 8.0?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- How should passwords be stored in PHP?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What are union types in PHP 8 and how do you use them?
- What are enums in PHP 8.1? Explain pure vs backed enums.