How XSS attacks exploit unescaped output in PHP - Performance & Efficiency
We want to understand how the cost of processing unescaped output grows as input size increases in PHP code vulnerable to XSS.
Specifically, how does the program handle larger inputs that include malicious scripts?
Analyze the time complexity of the following PHP snippet that outputs user input without escaping.
<?php
$userInput = $_GET['comment'];
echo "<div>" . $userInput . "</div>";
?>
This code takes a comment from the user and prints it directly inside a div without escaping special characters.
Look for operations that repeat or scale with input size.
- Primary operation: Concatenation and output of the entire user input string.
- How many times: Once per request, but the length of the input string affects the amount of data processed.
The time to output grows roughly in direct proportion to the length of the input string.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 characters | 10 operations (output each character) |
| 100 characters | 100 operations |
| 1000 characters | 1000 operations |
Pattern observation: The work grows linearly as input size increases.
Time Complexity: O(n)
This means the time to process and output the input grows directly with the input size.
[X] Wrong: "Outputting unescaped input is always fast and safe regardless of input size."
[OK] Correct: Large inputs take longer to process and can include harmful scripts that exploit the lack of escaping, causing security risks and performance issues.
Understanding how input size affects processing time and security helps you write safer, more efficient code and explain risks clearly in interviews.
What if we added escaping functions to sanitize the input before output? How would the time complexity change?