Consider this PHP code that outputs user input directly without escaping. What will be the output when the input is <script>alert('XSS')</script>?
<?php $user_input = "<script>alert('XSS')</script>"; echo "User says: $user_input"; ?>
Think about how PHP outputs strings and what happens if HTML tags are included in the string.
The code outputs the raw user input directly. Since the input contains HTML script tags, the browser will interpret and run the script, so the output is exactly User says: <script>alert('XSS')</script> rendered as HTML, which triggers the alert.
Why does outputting user input directly without escaping or sanitizing cause Cross-Site Scripting (XSS) vulnerabilities?
Think about how browsers handle HTML and JavaScript inside web pages.
When user input is output without escaping, any HTML or JavaScript code inside it is interpreted and executed by the browser, allowing attackers to run malicious scripts.
Look at this PHP code that outputs a username. What security issue does it have?
<?php $username = $_GET['user']; echo "Welcome, $username!"; ?>
Consider what happens if the user input contains HTML or JavaScript.
The code outputs user input directly without escaping, so if the input contains malicious scripts, they will run in the browser, causing XSS.
Choose the PHP code snippet that safely outputs user input to prevent XSS attacks.
Think about which function converts special characters to HTML entities including quotes.
htmlspecialchars with ENT_QUOTES converts special characters including quotes to safe HTML entities, preventing scripts from running.
This PHP code collects user inputs into an array but does not escape them. How many items will the array contain?
<?php $inputs = []; $inputs[] = '<script>alert(1)</script>'; $inputs[] = 'hello'; $inputs[] = '<img src=x onerror=alert(2)>'; $inputs[] = 'world'; ?>
Count how many times the array is appended.
The code adds four items to the array, including strings with HTML tags. Escaping is not related to the count of items.