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
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 -->
🌐
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 (').
Discussions

Pass a PHP variable to a JavaScript variable - Stack Overflow
I'm pretty sure that More on stackoverflow.com
🌐 stackoverflow.com
October 23, 2014
javascript - JS inside PHP Escape String (for functions) - Stack Overflow
I have a PHP script that generates some Javascript for me in a manner like this: foreach ($array as $element) { echo ' More on stackoverflow.com
🌐 stackoverflow.com
plugins - How to proper escape echo inside a javascript tag - WordPress Development Stack Exchange
In this case where you're embedding the value in a JS string, all we can say for sure is that if the value has any chance of containing a ", we want to escape those quotations such that the data could not execute arbitrary JavaScript. WordPress's esc_js() may be a good escaping selection here. When possible, it is recommended that you transfer data from PHP ... More on wordpress.stackexchange.com
🌐 wordpress.stackexchange.com
August 25, 2022
php - Preventing XSS attacks with proper escaping - Code Review Stack Exchange
You aren't escaping ; for JavaScript strings, that can be used to break out of the context. More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
December 2, 2014
🌐
GitHub
gist.github.com › Chengings › 9599473
Escape php string to javascript string · GitHub
Escape php string to javascript string. GitHub Gist: instantly share code, notes, and snippets.
🌐
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().
🌐
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.
🌐
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-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 - <?php $user_action = "delete"; // Potentially malicious input $item_id = 789; // Basic escaping for literal JS code execution context $escaped_action = addslashes($user_action); $escaped_item_id = intval($item_id); // Ensure it's a number ?> <script> function processItem(action, id) { console.log("Processing item " + id + " with action: " + action); } processItem('<?php echo $escaped_action; ?>', <?php echo $escaped_item_id; ?>); </script> A common gotcha is relying solely on addslashes(). While it handles simple string literals, it’s not a universal solution. If your dynamic content isn’t strictly confined to a JavaScript string, other injection vectors might open up.
🌐
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; }
Find elsewhere
🌐
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:
🌐
WordPress
developer.wordpress.org › reference › functions › esc_js
esc_js() – Function - WordPress Developer Resources
wp-includes/formatting.php · Expand code · Copy · function esc_js( $text ) { $safe_text = wp_check_invalid_utf8( $text ); $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT ); $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) ); $safe_text = str_replace( "\r", '', $safe_text ); $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) ); /** * Filters a string cleaned and escaped for output in JavaScript.
🌐
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
Consider this JavaScript snippet: var message = "User said: 'Hello World!'";. To correctly embed this in PHP using double quotes, you'd write: <?php $js_string = "var message = \"User said: 'Hello World!'\";"; echo $js_string; ?> A frequent pitfall is neglecting to escape backslashes (\) themselves.
🌐
MojoAuth
mojoauth.com › escaping › php-string-escaping-in-javascript-in-browser
PHP String Escaping in JavaScript in Browser | Escaping Methods in Programming Languages
We will cover essential techniques for escaping special characters, preventing common pitfalls like XSS vulnerabilities, and improving the overall reliability of your code. Whether you’re a beginner or an experienced developer, this guide will equip you with the knowledge you need to handle PHP strings confidently in a JavaScript environment.
🌐
The Art of Web
the-art-of-web.com › javascript › escape
Escaping Special Characters < JavaScript | The Art of Web
All functions have a complementary 'decode' function that pretty much does the opposite. Another essential PHP function that comes in handy when passing data to JavaScript is addslashes which will add a backslash before: backslashes, single- and double-quotes.
🌐
Texelate
texelate.co.uk › blog › convert-php-strings-for-use-as-javascript-strings
Convert PHP strings for use as JavaScript strings | Texelate
<?php function formatJavaScript($string, $doubleQuotesContext = true, $addQuotes = false) { // It must be a string else numbers get mangled $string = (string) $string; // Encode as standard JSON, double quotes $string = json_encode($string); // Remove " from start and end" $string = mb_substr($string, 1, -1); // If using single quotes, reaplce " with ' and escape if ($doubleQuotesContext === false) { // Remove \ from " $string = str_replace('\"', '"', $string); // Escape single quotes $string = str_replace("'", "\'", $string); } if ($addQuotes === true) { if ($doubleQuotesContext === true) { $string = '"' .
🌐
Inanimatt
inanimatt.com › php-output-escaping.html
Output escaping - inanimatt.com
PHP doesn't have a built-in way to escape Javascript, but you can cheat and use the json_encode() function. There are some important caveats: Make sure your output is a string.
Top answer
1 of 1
1

Whether and how something should be escaped is largely dependent on where the data came from and how it will be used. It's primary function is to prevent data from being interpreted as a part of the code or mechanism which the data will be contained in - we don't want a value used in a URL's querystring containing &s to be interpreted as additional parameters, for instance. Or data which will be inserted into an HTML attribute to contain quotations that would effectively enable it to potentially close the attribute quotation and have it's contents interpreted as markup.

In this case where you're embedding the value in a JS string, all we can say for sure is that if the value has any chance of containing a ", we want to escape those quotations such that the data could not execute arbitrary JavaScript. WordPress's esc_js() may be a good escaping selection here.

When possible, it is recommended that you transfer data from PHP to JS using a wp_add_inline_script() call. We can mimic the functionality of wp_localize_script() by json_encoding() an associative array of data into a JSON object (which might not be necessary if you only have one/a few values, or the script for which you're inlining data depends on specific globals/variables):

function wpse408964_enqueue_scripts() {
  $result = //...;

  wp_enqueue_script( 'my-static-script', plugins_url( 'js/static.js', __FILE__ ) );
  wp_add_inline_script(
    'my-static-script',
    'const MYDATA = ' . json_encode( array(
      'sel' => esc_js( $result[0] )
    ) ),
    'before'
  );
}

However, this may not be possible depending on your specific use-case.