XSS occurs when untrusted content is interpreted as HTML or script in a browser.
What It Does
XSS occurs when untrusted content is interpreted as HTML or script in a browser. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Escape untrusted text in an HTML text node.
<?php
$query = '<script>alert(1)</script>';
echo htmlspecialchars($query, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
Example 2: Another Case
Escape content in quoted HTML attributes; JavaScript and URL contexts need separate rules.
<?php
$label = '" onclick="alert(1)';
echo '<input value="' . htmlspecialchars($label, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
Practical Example: Putting It to Use
Validate allowed URL schemes before HTML-escaping a link attribute.
<?php
$raw = 'javascript:alert(1)';
$scheme = strtolower((string) parse_url($raw, PHP_URL_SCHEME));
if (!in_array($scheme, ['http', 'https'], true)) echo 'Blocked dangerous URL';
Important Behavior and Edge Cases
Escape for the exact output context and validate URL schemes; HTML escaping is not safe JavaScript encoding.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Preventing Cross-Site Scripting in PHP | XSS occurs when untrusted content is interpreted as HTML or script in a browser. |
| Related approach | A restrictive CSP adds defense in depth but does not replace output escaping. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Preventing Cross-Site Scripting in PHP | Escape for the exact output context and validate URL schemes; HTML escaping is not safe JavaScript encoding. |
| Assuming a related mechanism has the same behavior | A restrictive CSP adds defense in depth but does not replace output escaping. |
Key Takeaways
- XSS occurs when untrusted content is interpreted as HTML or script in a browser.
- Escape for the exact output context and validate URL schemes; HTML escaping is not safe JavaScript encoding.
- A restrictive CSP adds defense in depth but does not replace output escaping.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.