3

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!

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I've +1ed for the addslashes() part, even before reading the rest :)
2

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. -Spudley

I think the function you're looking for is htmlentities()

<?=htmlentities($desc1, ENT_QUOTES)?>

https://www.php.net/htmlentities

2 Comments

Thanks! Easiest answer to implement and perfect results :)
This answer contains correct information but is incomplete. Using addslashes() to generate JavaScript strings is wrong and will break your page randomly.
2

You are generating a JavaScript string encoded as HTML so you need to encode twice:

Comments

2

Use json_encode to output variables from the backend in JavaScript:

<tr onclick='afterProductSelection(<? print json_encode($desc1); ?>)'>

N.B.: For string output there is no need for extra quotes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.