---
title: Escape Data By Output Context
impact: MEDIUM
impactDescription: ensures correct encoding for each output context to prevent XSS and injection
tags: xss, escaping, context, encoding, security, php
---

## Escape Data By Output Context

Using the wrong escaping strategy for a given context is a common security mistake. For example, using HTML encoding (`htmlspecialchars`) inside a JavaScript block or in an HTTP header does not provide adequate protection.

**Incorrect (wrong encoding for specific context):**

```php
$input = $_GET['user']; // Attacker input: "; alert(1); //

// WRONG: Using HTML escaping in a JavaScript context
$escaped = htmlspecialchars($input);
echo "<script>var name = '{$escaped}';</script>"; 
// Result: var name = '&quot;; alert(1); //'; -> Still potentially breaks logic or remains vulnerable

// WRONG: No sanitization for HTTP headers
header("X-Custom-Data: " . $input); // Header injection via CRLF
```

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

```php
// 1. HTML Body Context
echo "<div>" . htmlspecialchars($input, ENT_QUOTES, 'UTF-8') . "</div>";

// 2. JavaScript Context (Always use JSON encoding)
$jsonInput = json_encode($input);
echo "<script>var name = {$jsonInput};</script>";

// 3. URL Context
echo "<a href='/profile?name=" . urlencode($input) . "'>View</a>";

// 4. HTTP Header Context (Strip newlines)
$safeHeader = str_replace(["\r", "\n"], '', $input);
header("X-Custom-Data: " . $safeHeader);

// 5. Shell Argument Context (If using exec/system)
$safeArg = escapeshellarg($input);
system("echo " . $safeArg);
```

**Context Selection Guide:**

| Context | Recommended PHP Function | Why? |
|---------|--------------------------|------|
| **HTML Content** | `htmlspecialchars(..., ENT_QUOTES)` | Converts `< > & " '` to entities. |
| **JS Variable** | `json_encode()` | Safely wraps strings in quotes and escapes internal quotes/slashes. |
| **URL Parameter** | `urlencode()` | Converts special chars to `%XX` format. |
| **HTTP Header** | `str_replace(["\r", "\n"], '', $input)` | Prevents CRLF injection (Splitting). |
| **Shell Command** | `escapeshellarg()` | Adds quotes and escapes shells meta-characters. |

**Tools:** PHPStan, Psalm, SonarQube, Manual Security Review
