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 -->
🌐
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.
🌐
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.
🌐
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.
🌐
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.
🌐
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.
🌐
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'); }); }); });
🌐
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 (').
Find elsewhere
🌐
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; }
🌐
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>
🌐
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.
🌐
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().
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.

🌐
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.
🌐
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.