---
title: Output Encoding Before Interpreter Use
impact: HIGH
impactDescription: prevents XSS and other injection attacks in the browser
tags: xss, encoding, output, html, security, php
---

## Output Encoding Before Interpreter Use

Cross-Site Scripting (XSS) and other injection attacks occur when unescaped user-controlled data is interpreted as code by the browser. All data must be encoded or escaped according to the context where it is being displayed.

**Incorrect (no encoding):**

```php
// XSS vulnerability in plain PHP
echo "<h1>Results for: " . $_GET['q'] . "</h1>";

// Blade "unescaped" output for user input
{!! $userInput !!} 

// Injecting into JavaScript without encoding
echo "<script>const name = '" . $userName . "';</script>";
// Attacker in $userName: '; alert(1); //
```

**Correct (context-aware encoding):**

```php
// 1. HTML Body context (plain PHP)
echo "<h1>Results for: " . htmlspecialchars($_GET['q'], ENT_QUOTES, 'UTF-8') . "</h1>";

// 2. Blade (Recommended)
// Auto-escapes using htmlspecialchars internally
<h1>Results for: {{ $query }}</h1>

// 3. If you MUST output HTML, use a sanitizer (e.g. HTML Purifier)
$purifier = new HTMLPurifier();
echo $purifier->purify($userHtml);

// 4. JavaScript context
// Always use json_encode for passing data to JS
?>
<script>
    const name = <?php echo json_encode($userName); ?>;
</script>
<?php

// 5. URL context
$url = "/profile?user=" . urlencode($username);
```

**Encoding by Context:**

| Context | Encoding Method | Result Example |
|---------|-----------------|----------------|
| **HTML Body** | `htmlspecialchars()` | `<` becomes `&lt;` |
| **HTML Attribute** | `htmlspecialchars(..., ENT_QUOTES)` | `"` becomes `&quot;` |
| **JavaScript** | `json_encode()` | String becomes `"string"` with quotes |
| **URL Parameter** | `urlencode()` | Spaces become `+` or `%20` |

**Tools:** HTML Purifier, Blade Template Engine, PHP_CodeSniffer, SonarQube
