Get up to 80 % extra points for free! More info:

Discussion: Why doesn't the htmlspecialchars function convert single quotes to entities by default?

Matthias Quintero:11/8/2016 14:08

I know that the the htmlspecialchars() function is able to convert single quotes to entities if ENT_QUOTES is added into the second parameter. However, wouldn't it make more sense to make it convert them by default and then have an option to leave them as is? Is there a valid reason as to why they set it up this way? Because I can come up with many, many more instances in which I would need converted single quotes than actual strings within a string...

Just to be clear, I think this should be converted by default:

$str = "Then he told me, 'Get away from me!'.";
htmlspecialchars($str); /* not like this: htmlspecialchars($str, ENT_QUOTES) */

Mainly because it wouldn't make any sense for the quote within the string to be treated like a string as well.

11/8/2016 14:08
David Capka team
Replies to Matthias Quintero
David Capka:11/8/2016 14:32

I believe it's not default because of backward compatibility, maybe they just didn't realize it's necessary and they can't change it now. The best solution is to create some custom function for it which would call htmlspecialchars() with appropriate parameters.

I'd like to mention some cases when it's really wise to escape single quotes since they can lead to some kinds of XSS. Consider this example:

<button onclick="alert('<?= htmlspecialchars($value) ?>');" />

If there was an apostrophe in the $value, it could lead to the JavaScript injection if used htmlspecialchars() in the default configuration.

Edited 11/8/2016 14:33
Up Reply
11/8/2016 14:32
You can walk through a storm and feel the wind but you know you are not the wind.
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

2 messages from 2 displayed.