0

I have post content in sql database where special char are already escaped with htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8');.

I use the php template engine Twig to render my template (with no framework, only php vanilla). Here is my problem : Twig escape a second time the ampersand "&" char, which result in display ugly string in the webpage, like : Here is a <script>window.alert("hello");</script> test

When i use the filter raw in Twig, that solve the problem. But after some research, people say that it is not safe at all, but I can't find a real solution.

So my question is : can I use raw filter in my case, because $content is already escaped by PHP ? Or there is a better and safer way to do this ?

I try to use raw filter and that work, also {% autoescape false %} work, but I want to be really sure that it is safe to render.

DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • If the content in your database is not user-generated, then yes it's safe to use the filter `raw`. If the content is user-generated then u would need to sanitize your input before inserting it in the database anyway. – DarkBee Mar 14 '23 at 10:11
  • Yes, it is user-generated. I only use htmlspecialchars to insert it into database for the moment, I should do more ? – Shaun-maker Mar 14 '23 at 10:21
  • `htmlspecialchars` doesn't add anything to the "security" aspect of this. As I said in my first comment, you'll need to [sanitize the input](https://stackoverflow.com/questions/129677/how-can-i-sanitize-user-input-with-php) – DarkBee Mar 14 '23 at 10:26
  • Okay, so if I understand well your link, I should not use htmlspecialchars for input data, and only use PDO statement (I already do that) ? And then, to display the content, use "escape" twig filter ? – Shaun-maker Mar 14 '23 at 11:37
  • That's not what sanitazing means, it means you strip out every tag you don't want an user can post, e.g. ` – DarkBee Mar 14 '23 at 12:34
  • Thanks for your answers ! So I should use strip_tags for example, before insert user input to database, instead of htmlspecialchars ? – Shaun-maker Mar 14 '23 at 12:45

0 Answers0