What is XSS and how do you prevent it in PHP?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex PHP topics. It also reveals how well you can explain technical ideas to non-experts.
Answer
Cross-Site Scripting (XSS) is a security vulnerability where an attacker injects malicious JavaScript into web pages viewed by other users. If you output user-supplied data directly to HTML without sanitization, an attacker could inject <script>stealCookies()</script>. Prevention in PHP: always escape output using htmlspecialchars($data, ENT_QUOTES, "UTF-8") before rendering user data in HTML — this converts <, >, ", ', and & into their HTML entity equivalents. Also use Content Security Policy (CSP) headers, set the HttpOnly flag on cookies, and validate/sanitize all input. Never trust user input.
Common Mistake
Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong PHP candidates.
Previous
What are prepared statements and why are they important?
Next
What is SQL injection and how do you prevent it in PHP?