Let me start by saying Javascript is not my strong point, and all of the searches I have done for information on this topic have resulted in how to deal with url encode/decoding strings.
I’m having trouble with some code similar to the following:
<a href="#" onclick="<?php echo "alert(''');"; ?>">test</>
I would expect that since the value being passed to alert is url encoded, that when clicking the link an alert box would be shown with the value ' in it.
It turns out that because the it is between the quotes for the onclick, the browser is decoding ' to a single quote before executing. Basically resulting in the code being alert('''); which obviously breaks horribly.
The following works just fine.
<script>alert(''');</script>
Firstly, is there a way to disable this behaviour, or a clever workaround? (I’m guessing not)
My current solution is to decode the html encoded string, apply slashes to quotes, and then re-encode it. Obviously not very elegant.
Better solutions would be much appreciated.
That’s the expected behaviour. HTML entities in the HTML source code are automatically converted when the browser parses the attribute. This allows website developers to include special characters, such as quotes in an attribute, without breaking the page.
Use
htmlspecialcharsto get the desired effect: