Search code examples
phphtml-entitieshtml-injections

PHP - Having more than one htmlentities() in your code


I just came across building a CRUD application in PHP, and the instructor was reminding us about the use of htmlentities() in order to avoid HTML injections, and he then goes to say that htmlentities shouldnt be called more than once in your code, my question is very simple...why?

Cheers


Solution

  • Because calling it a second time on the same value can double-encode it.

    Taking the example from the PHP docs:

    $str = "A 'quote' is <b>bold</b>";
    
    $firstEntity = htmlentities($str);
    // Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
    

    Now if we run that through htmlentities() again it will encode the ampersands that the first htmlentities() call created and you'll end up with a double-encoded string:

    $secondEntity = htmlentities($firstEntity);
    // Outputs: A 'quote' is &amp;lt;b&amp;gt;bold&amp;lt;/b&amp;gt;