This is my source code:

<!DOCTYPE html>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    var output = "";
    if (isset($_GET['q'])) {
      printf('output = "%s";', htmlspecialchars($_GET['q'],ENT_QUOTES, 'UTF-8'));

    $(function()  {
    <p id="output"></p>

When I send q=\x3cscript\x3ealert(1)\x3c/script\x3e to my script, the alert is fired. How can I prevent this?


Escaping is context sensitive. You are escaping for HTML, but are using the variable in Javascript. Instead, correctly encode for JavaScript using json_encode:

printf('output = %s;', json_encode($_GET['q']));

Also, you are using the html function even though you don't seem to want HTML at all. What you probably want is the text function:

  • Just a thought: would json_encode catch </script><script>alert(1) ? – paj28 Mar 22 '17 at 9:54
  • 1
    @paj28 Yes, it encodes the slash as \/. – Sjoerd Mar 22 '17 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.