Search code examples
phpsecurityhtmlspecialchars

Is using htmlspecialchars() sufficient in all situations?


My users are allowed to insert anything into my database.

So using a whitelist / blacklist of characters is not an option.

I'm not worried (covered it) about the database end (SQL injection), but rather code injection in my pages.

Are there any situations where htmlspecialchars() wouldn't be sufficient to prevent code injection?


Solution

  • Plain htmlspecialchars is not sufficient when inserting user text into single quoted attributes. You need to add ENT_QUOTES in that case and you need to pass the encoding.

    <tag attr='<?php echo htmlspecialchars($usertext);?>'> //dangerous if ENT_QUOTES is not used
    

    When inserting user text into javascript/json as string you'll need additional escaping.

    I think it fails for stange character sets too. But if you use one of the usual charsets UTF-8, Latin1,... it will work as expected.