Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping quotation marks in PHP for JavaScript function argument

I'm having trouble escaping a quotation mark in PHP. I have a table of products and each row has an onclick function, with the name of the product as the argument.

The name contains the length which is measured in inches, so the name contains a quotation mark. I wrapped an addslashes() around the string. This adds a backslash before the quotation mark but for some reason it doesn't seem to escape the character!

Here's a snippet of my code:

<?$desc1 = addslashes($row['Desc1']);?>

<tr class='tableRow' onclick='afterProductSelection("<?=$desc1?>")'>

<td><?=$row['Desc1']?></td>

When I inspect element in Google Chrome, the colour of the syntax indicates that this has not been escaped, clicking on it gives me a syntax error.

enter image description here

Probably something simple that I'm missing. Hope you can help!

like image 456
Dan Johnson Avatar asked Sep 15 '26 01:09

Dan Johnson


1 Answers

There are a lot of different cases where you need to escape a string. addslashes() is the wrong answer to pretty much all of them.

The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything.

In your particular case, since you're creating Javascript data from PHP, use json_encode().

json_encode() will take a PHP variable (whether it's a string, array, object or whatever) and convert it into a JSON string. A JSON string is basically fully escaped Javascript variable, including the quotes around your strings, etc. This is what you need to do.

like image 143
Spudley Avatar answered Sep 16 '26 13:09

Spudley