---
title: Output Encoding For Dynamic JS/JSON
impact: HIGH
impactDescription: prevents code injection when embedding server-side data into JavaScript
tags: xss, javascript, json, encoding, security, php
---

## Output Encoding For Dynamic JS/JSON

Embedding PHP data directly into JavaScript tags requires proper encoding to prevent Cross-Site Scripting (XSS). Simple string interpolation or manual quoting is dangerous. The safest way to pass complex data (strings, arrays, objects) from PHP to JavaScript is using `json_encode`.

**Incorrect (unescaped data in inline Script):**

```php
// VULNERABLE: Direct interpolation in JS
$username = "</script><script>alert('XSS')</script>";
?>
<script>
    var current_user = "<?php echo $username; ?>"; 
</script>
<?php
// Result: var current_user = "</script><script>alert('XSS')</script>"; 
// The browser closes the first script tag and executes the second one!
```

**Correct (using json_encode):**

```php
$userData = [
    'name' => $user->name,
    'email' => $user->email,
    'roles' => $user->getRoles()
];

// 1. Safe JSON encoding for inline script
?>
<script>
    // json_encode automatically adds quotes and escapes dangerous characters
    var appConfig = <?php echo json_encode($userData, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
</script>

<?php
// 2. Best Practice: Using data attributes (Recommended for SPAs/Vue/React)
?>
<div id="user-profile" data-user="<?php echo htmlspecialchars(json_encode($userData), ENT_QUOTES, 'UTF-8'); ?>">
    <!-- JS will read this via element.dataset.user -->
</div>

<?php
// 3. In Laravel Blade
?>
<script>
    var user = @json($userData);
</script>
```

**Why `json_encode`?**
- It handles strings, integers, booleans, and nested arrays/objects correctly for JavaScript.
- It escapes backslashes and quotes automatically.
- Using flags like `JSON_HEX_TAG` prevents `</script>` tags from breaking your own script block.

**Tools:** Laravel Blade `@json` directive, SonarQube, Manual Security Review
