26

lets imagine a form editor, it can edit available values. If the data contains " character (double quote) it "destroys" HTML code. I meant, lets check the code: so I generate HTML:

onclick="var a = prompt('New value: ', '<?php echo addslashes($rec[$i]); ?>'); if (a != null)....

and it results in

onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....

and this makes JS work impossible, so that it ruins the code. With single qoute ' it works OK. mysql real escape does the same. How to escape any string so that it won't ruin javascript?


json_encode looked OK, but I must be doing something wrong, its still bad: heres a screenshot how Firefox sees it - it inserts a "bad" double quote! The value is just a simple number:

http://img402.imageshack.us/img402/5577/aaaahf.gif

and I did used:

('Ird be az új nevet:', <?php echo json_encode($rec['NAME']); ?>); if (a) { 
Dori
  • 915
  • 1
  • 12
  • 20
user893856
  • 1,039
  • 3
  • 15
  • 21
  • 1
    possible duplicate of [Pass a PHP string to a Javascript variable (including escaping newlines)](http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-including-escaping-newlines) – John Flatness Aug 16 '11 at 22:32
  • 2
    not exactly a duplicate, when its used inside an HTML attribute it requires an extra step of escaping – shesek Aug 16 '11 at 22:49

4 Answers4

41

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)

rymo
  • 3,285
  • 2
  • 36
  • 40
shesek
  • 4,584
  • 1
  • 28
  • 27
  • Thanks for the typo fix, but I rejected it because I added the last paragraph after you edited it. I added your change manually. – shesek Aug 16 '11 at 23:03
1
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....

Your problem is highlighted in bold. You can't quote a variable declaration you shouldn't need to escape the double quote once this is removed since it is within single quotes. Should look like this -

onclick="newFunc();"
<script>
function newFunc()  {
var a = prompt('New value: ', 'aaaa"aaa'); 
if (a != null) { v....
}
</script>
  • I affraid I dont really understand. Ok, I wont use any escape, but its now onclick="var a = prompt('New value: ', 'áááá"áááá'); if (a != null) { spoiled again – user893856 Aug 16 '11 at 22:19
  • the only thing you should put in the onclick parameter is a call to a function that handles everything.. like this – Marshall House Aug 16 '11 at 22:24
1
...onclick="new_func();"...
<script>
function new_func() {
    var a = prompt('new value:','<?php code; ?>');
    if (a) { <!--javascript code--> } else { <!--javascript code--> }
}
</script>
1

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 $rec[$i]; ?>');
        // Although the following could be safer
        var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
        if (a) { <!--javascript code--> }
        else { <!--javascript code--> }
    }
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->
Robin Winslow
  • 10,908
  • 8
  • 62
  • 91
  • 2
    `addslashes()` doesn't always work as expected for encoding strings to javascript. `json_encode()` is much more reliable. Do note that it adds the quotes around the strings, so the value returned from `json_encode()` shouldn't be wrapped in another `''` – shesek Aug 16 '11 at 22:40