The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:

<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';

That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)

Answer from shesek on Stack Overflow
๐ŸŒ
Compile7
compile7.org โ€บ escaping โ€บ how-to-use-php-string-escaping-in-javascript-in-browser
A Comprehensive Resource on How to use PHP String Escaping in JavaScript in Browser - Compile7
October 6, 2025 - A common mistake is echoing strings directly, like var data = '<?php echo $user_comment; ?>';. This leaves a gap for attackers. Always use json_encode() for any PHP variable you pass to client-side JavaScript. Passing structured data from PHP to your browser-side JavaScript is straightforward by encoding entire PHP arrays or objects into JSON.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 38885945 โ€บ post-escaped-javascript-array-and-unescape-it-in-php
Post escaped Javascript array and unescape it in PHP - Stack Overflow
I escaped the values to allow users to enter in special characters and then placed them into an array that is stringified and then posted. $(document).ready(function() { $("#submit").click(function() { var BuilderName = escape($('[name=BuilderName]').val()); var OwnersName = escape($('[name=OwnersName]').val()); var arraydata = [BuilderName, OwnersName]; $.post("DCF_Update_Query.php", { data: JSON.stringify(arraydata) }, function() { alert('Successful'); }).fail(function() { alert('Failed'); }); }); });
Discussions

javascript - JS inside PHP Escape String (for functions) - Stack Overflow
You shouldn't need to add any quotes to the values manually; JSON strings are valid JavaScript literals. 2013-06-25T07:13:12.517Z+00:00 ... It turned out that you actually have to. 2013-06-25T08:44:45.65Z+00:00 ... Save this answer. ... Show activity on this post. Never echo JS from PHP. Escape ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
php - Preventing XSS attacks with proper escaping - Code Review Stack Exchange
The following page simulates XSS attacks and successfully (?) prevents them. I want to know if I've missed any other major attack vectors (or small ones) and/or if anyone has suggestions as to impr... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
December 2, 2014
Pass a PHP variable to a JavaScript variable - Stack Overflow
What is the easiest way to encode a PHP string for output to a JavaScript variable? I have a PHP string which includes quotes and newlines. I need the contents of this string to be put into a More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 23, 2014
PHP equivalent for javascript escape/unescape - Stack Overflow
Let's say I have a string: something When I escape it in JS I get this: something so I can use this code in JS to decode it: document.write(unescape('somethin%... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 4
47

The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:

<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';

That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)

2 of 4
3

I'm really just re-wording what @Marshall House says here, but:

In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that @Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.

E.g.:

<script>
    // This is a function, wrapping your code to be called onclick.
    function doOnClickStuff() {
        // You should no longer need to escape your string. E.g.:
        //var a = prompt('new value:','<?php echo i]; ?>');
        // Although the following could be safer
        var a = prompt('new value:',<?php json_encode(i]); ?>);
        if (a) { <!--javascript code--> }
        else { <!--javascript code--> }
    }
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->
๐ŸŒ
GitHub
gist.github.com โ€บ Chengings โ€บ 9599473
Escape php string to javascript string ยท GitHub
Escape php string to javascript string ยท Raw ยท gistfile1.php ยท This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
๐ŸŒ
SSOJet
ssojet.com โ€บ escaping โ€บ javascript-string-escaping-in-php
JavaScript String Escaping in PHP | Escaping Techniques in Programming
While addslashes() works for simple cases, remember that json_encode() is generally the more robust and recommended method for passing complex or structured data between PHP and JavaScript due to its comprehensive handling of various data types and special characters. Always ensure your embedded strings are correctly delimited and escaped to maintain valid JavaScript syntax.
๐ŸŒ
Compile7
compile7.org โ€บ escaping โ€บ how-to-use-javascript-string-escaping-in-php
How to use JavaScript String Escaping in PHP | Escaping Methods in Programming Languages
The most reliable method is to serialize your JavaScript data into JSON. In JavaScript, JSON.stringify() converts your data into a JSON string. PHP then uses json_decode() to parse this string back into a usable PHP array or object.
๐ŸŒ
Creativepulse
creativepulse.gr โ€บ en โ€บ blog โ€บ 2013 โ€บ how-to-properly-escape-javascript-json-strings-in-php-scripts
How to properly escape JavaScript (JSON) strings in PHP scripts - Blog - Creative Pulse
November 20, 2013 - But this little script goes one step beyond that, it also escapes the inequality symbols < > which have a special meaning in HTML and they may cause problems if left unescaped. So here it is, enjoy! if (!function_exists('json_esc')) { function json_esc($input, $esc_html = true) { $result = ''; if (!is_string($input)) { $input = (string) $input; } $conv = array("\x08" => '\\b', "\t" => '\\t', "\n" => '\\n', "\f" => '\\f', "\r" => '\\r', '"' => '\\"', "'" => "\\'", '\\' => '\\\\'); if ($esc_html) { $conv['<'] = '\\u003C'; $conv['>'] = '\\u003E'; } for ($i = 0, $len = strlen($input); $i < $len; $i++) { if (isset($conv[$input[$i]])) { $result .= $conv[$input[$i]]; } else if ($input[$i] < ' ') { $result .= sprintf('\\ux', ord($input[$i])); } else { $result .= $input[$i]; } } return $result; } }
Find elsewhere
๐ŸŒ
SSOJet
ssojet.com โ€บ escaping โ€บ php-string-escaping-in-javascript-in-browser
PHP String Escaping in JavaScript in Browser | Escaping Techniques in Programming
Specifically, to safely include a PHP string variable within a JavaScript single-quoted string, you'll want to use htmlspecialchars($phpString, ENT_QUOTES). This flag tells htmlspecialchars to escape both double quotes (") and single quotes (').
๐ŸŒ
Defuse Security
defuse.ca โ€บ blog โ€บ escaping-string-literals-for-javascript-in-php.html
Escaping String Literals (for JavaScript) in PHP
July 1, 2012 - Use the following code to escape user-supplied input before inserting it into a JavaScript string literal. <?php function js_string_escape($data) { $safe = ""; for($i = 0; $i < strlen($data); $i++) { if(ctype_alnum($data[$i])) $safe .= $data[$i]; else $safe .= sprintf("\\xX", ord($data[$i])); } return $safe; }
๐ŸŒ
MojoAuth
mojoauth.com โ€บ escaping โ€บ javascript-string-escaping-in-php
JavaScript String Escaping in PHP | Escaping Methods in Programming Languages
Common characters that require escaping include: Single Quote ('): Use \' to include in a string. Double Quote ("): Use \" to include in a string. Backslash (``): Use \ to include a backslash. Newline (\n): Represents a new line. Tab (\t): Represents a horizontal tab. When generating JavaScript strings within PHP, itโ€™s essential to properly escape these characters to avoid syntax errors.
๐ŸŒ
The Art of Web
the-art-of-web.com โ€บ javascript โ€บ escape
Escaping Special Characters < JavaScript | The Art of Web
A guide to escaping special characters in JavaScript and PHP. Comparing JavaScript escape with PHP urlencode and rawurlencode. Converting spaces, quotes and other entities.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 14087482 โ€บ how-to-escape-html-elements-when-fetching-an-array-in-php-using-javascript
jquery - How to escape HTML elements when fetching an array in PHP using Javascript? - Stack Overflow
I tried this and replaced the < with &lt; and > with &gt; but I still get a parse error. I do not now how to incorporate the nifty function you linked to in my javascript above. Could you show me how? Here is the error I get with "hard coding" the brackets < and > <br /> <b>Parse error</b>: syntax error, unexpected '&'. Many Thanks.
๐ŸŒ
Reddit
reddit.com โ€บ r/phphelp โ€บ php is adding escape characters to my json string and i have no idea why,
r/PHPhelp on Reddit: PHP is adding escape characters to my JSON string and I have no idea why,
April 18, 2023 -

I have a website that lets the user build a dynamic form (think tabs with widgets) and then reduce the whole thing to a string with json.stringify().

But when I pass it to PHP (on one of our two systems to make things weirder) it adds a mess of escape characters. For example:

  {\\"tab_type\\":\\"accordion\\",\\"options\\"{\\"tab::style\\":\\"color:0x8000ff00\\",  

When the correct formatting should look like:

 "type":"accordion","options":{"tab::style":"color:0x8000ff00" 

The json is stringified properly on the JS side but it adds the slashes as soon as I look at the variable in the GET/POST on the PHP side.

๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ php_string_escape.asp
PHP - Escape Characters
In PHP, an escape character is a backslash \ followed by the character you want to insert. An example of an illegal character is a double quote inside a string that is surrounded by double quotes:
Top answer
1 of 3
3

The best way to do this is to encode the values using json_encode. Here is a simple example:

<?php
$name = "Jason's Bakery";

?>
<script>
   var name = <?php echo json_encode($name); ?>;
   DoSomethingWithName(name);
</script>

This can be used for integers, strings, and other values. Keep in mind that it will add quotes as needed, so you need to assemble and encode a "whole value at once". In your example of using the URLs, you need to use the PHP urlencode() function to encode them FIRST, and then pass it through json_encode to convert to a javascript value. And if you are placing that inside of an HTML attribute, like onclick, you need to further pass it through htmlspecialchars(..., ENT_QUOTES) and then place it in double quotes.

http://php.net/manual/en/function.json-encode.php

So for example, you need to build a URL in PHP and then use it in javascript...

<?php
$name = "Jason's \"Awesome\" Bakery";
$url = "http://site.com/page.php?name=" . urlencode($name);

?>
<script>
   var name = <?php echo json_encode($name); ?>;
   DoSomethingWithName(name);
</script>

<input type="button" onclick="<?php echo htmlspecialchars('window.location = ' . json_encode($url) . ';', ENT_QUOTES); ?>" value="Click Me" />

Which results in something like this:

<script>
   var name = "Jason's \"Awesome\" Bakery";
   DoSomethingWithName(name);
</script>

<input type="button" onclick="window.location = &quot;http:\/\/site.com\/page.php?name=Jason%27s+%22Awesome%22+Bakery&quot;;" value="Click Me" />

Needless to say, you do not want to do without these:

http://php.net/manual/en/function.json-encode.php
http://www.php.net/manual/en/function.urlencode.php
http://www.php.net/manual/en/function.htmlspecialchars.php

2 of 3
1

Due to respects of readability and future maintainability, I'd like to point out a few things which may help you out.

First, I see you're generating HTML elements in a PHP string. This isn't inherently bad, but when your string wraps across 2 or more lines, it becomes increasingly difficult to manage. Instead, you may want to think about escaping PHP for outputting HTML portions, and re-entering PHP for logical portions. You can escape PHP and enter HTML within if statements, function declarations etc, so there's really no good reason not to. Look at the following example (this solution also escapes the strings in an appropriate manner where its value can contain single quotes, double quotes or line breaks):

<?php

function urlFriendly($input) {
    return urlencode($input);
}

function jsFriendly($input, $urlFriendly = True) {
    $output = htmlentities($input, ENT_QUOTES);
    // Double quotes in PHP translate "\n" to a newline.
    // Single quotes in PHP keep the literal value.
    $output = str_replace("\r\n", '\n', $output); // Windows support
    $output = str_replace("\n", '\n', $output); // Linux support
    if($urlFriendly) { // Encode for use in URLs
      $output = urlFriendly($output);
    }
    return $output;
}

$vrj_name = 'vrj';
$messageContent_vrj = 'message content';
$from_email = 'from email';
$email = 'email';
$subject = 'subject line';

?>
<script type="text/javascript">
    function SelectRedirect() {
    switch(document.getElementById('s1').value) {
        case '?vrj_name=<?php print jsFriendly($vrj_name);?>':
            var toloc = '?vrj_name=<?php print jsFriendly($vrj_name);?>';
            toloc    += '&messageContent=<?php print jsFriendly($messageContent_vrj);?>'';
            toloc    += '&from_email=<?php print jsFriendly($from_email);?>';
            toloc    += '&email=<?php print jsFriendly($email);?>';
            toloc    += '&subject=<?php print jsFriendly($subject);?>';
            window.location = toloc;
            break;
    }
</script>
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.addslashes.php
PHP: addslashes - Manual
Never use addslashes function to escape values you are going to send to mysql. use mysql_real_escape_string or pg_escape at least if you are not using prepared queries yet. keep in mind that single quote is not the only special character that can break your sql query. and quotes are the only thing which addslashes care. ... To output a PHP variable to Javascript, use json_encode().