Search code examples
javascriptphphtmlonclickhtmlspecialchars

How do I use PHP to encode a string containing quotes to make it safe for inline 'onclick'?


I have a variable in a database that could potentially contain single or double quotes. When I retrieve the variable from the database, it is written with PHP into an inline "onclick" hander:

echo '<li><a onClick="a4e.duplicate_assignment('.$this_assignment['id'].',\''.htmlspecialchars($this_assignment['title'],ENT_QUOTES).'\',\'/assignments/'.$type.'/\');" href="javascript:void(0);">';echo '<i class="fa fa-copy"></i> Duplicate assignment</a></li>';

This produces HTML that looks like this in the page source:

<li><a onClick="a4e.duplicate_assignment(92,'ELLLO - &#039;If I had a million dollars&#039;','/assignments/cloze/');" href="javascript:void(0);"><i class="fa fa-copy"></i> Duplicate assignment</a></li>

However, clicking the link produces the following error in the console:

Uncaught SyntaxError: missing ) after argument list

I thought using the PHP function "htmlspecialchars" would mitigate this issue, but it doesn't seem to work.

Any help greatly appreciated.

P.S. It is not possible in this case to use a Javascript "onclick" handler - it has to be inline HTML. Also, it is not possible to ban the use of quotation marks in the variable value.


Solution

  • Try using the function:

    addslashes()
    

    EDIT: This method will take care of the quotes in the string itself, but may not be suitable if you need to retain quotes for HTML insertion. Read the docs carefully.

    http://php.net/manual/en/function.addslashes.php