How do I escape PHP data to be used in Javascript?

How do I escape PHP data to be used in Javascript?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Escaping PHP Data for JavaScript: A Practical Guide

You are likely facing a common friction point in modern web development: mixing server-side string interpolation with client-side scripting. Your specific scenario involves injecting a PHP variable directly into a jQuery .html() call. While this approach works for static content, it becomes dangerous the moment that PHP variable contains unescaped characters like single quotes, double quotes, or less-than signs.

If your $mystringWithSingleQuotes variable holds the value It's a test, and you pass it directly into the JavaScript string without modification, the browser interprets the quote as a terminator for the string literal rather than part of the text content. This breaks the code structure and can lead to syntax errors or, worse, XSS vulnerabilities if not handled correctly.

The core challenge is distinguishing between data destined for PHP output versus data destined for JavaScript execution. You cannot simply "escape single quotes" in isolation; you must escape the entire string according to JavaScript's rules. Relying on str_replace to swap ' with \' is a fragile pattern that fails if the variable itself contains backslashes or other special characters.

The Standard Approach: json_encode

The most robust solution for escaping data meant to be used in JavaScript is to leverage PHP's built-in ability to handle serialization. You should use the json_encode() function. This function does more than just escape quotes; it correctly handles newlines, backslashes, and unicode characters, outputting a valid JSON string that can be safely embedded in a script tag.

<?php
$mystringWithSingleQuotes = "It's a test with <script> tags";
$escapedString = json_encode($mystringWithSingleQuotes);

echo "<script type='text/javascript'>";
    $('#myElement').html('say hello to ' . $escapedString);
echo "</script>";
?>

In this example, json_encode transforms "It's a test with <script> tags" into \"It's a test with <script> tags\". The resulting output is a valid JSON string literal. When you concatenate this into your jQuery call, the quotes are properly escaped, and the HTML tags are treated as text content rather than executable code. This method is generally preferred because it abstracts away the complex rules of JavaScript escaping.

Using addslashes with Caveats

If you specifically need to target single quotes for a legacy reason or a very specific regex pattern, you might consider addslashes(). However, this function escapes backslashes (\) and double quotes (") as well. If your application environment already expects raw backslashes in certain contexts, this can introduce bugs. Furthermore, addslashes is not sufficient for escaping double quotes or newlines if those characters are present in your data.

Security Implications and Best Practices

The primary motivation for escaping variables before injecting them into JavaScript context is Cross-Site Scripting (XSS) prevention. If an attacker can control the content of $mystringWithSingleQuotes, they might inject malicious scripts like <script>alert('xss')</script>. Without proper escaping, the browser executes this code.

By using json_encode, you ensure that even if the input contains <script> tags or other JavaScript syntax, they are rendered as harmless text within the DOM element. This is significantly safer than manual string replacement.

While Laravel provides a Js facade and helper functions that handle much of this complexity automatically (e.g., Js::string($content)), the fundamental principle remains the same: never concatenate raw user input directly into a JavaScript string literal. Always serialize the data first. This ensures that your PHP output layer does not compromise the integrity of your JavaScript execution context.

Our network