Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly sanitize user input server side in Phoenix

I know how to sanitize user input client side but I would also do it on the server side. I know that the proper place to do it is using changeset but up to now I cannot find an example of how to do it properly for <script></script> tags and other potential harmful content like SQL injection. Because I want to allow users to change HTML content and save that HTML in the database I cannot use standard validation and I display raw HTML in the templates. Can someone give me an example?

like image 944
Paulo Janeiro Avatar asked Oct 24 '25 04:10

Paulo Janeiro


1 Answers

The phoenix_html library sanitizes user input by default:

<%= "<script>alert("hi")</script>" %>

Will display as:

&lt;script&gt;alert("hi")&lt;/script&gt;

This has to be overriden with raw/1:

<%= raw "<script>alert("hi")</script>" %>

Will display as

<script>alert("hi")</script>

If you would like to do this yourself (outside of an EEx template for example), you can use html_escape/1.

like image 147
Gazler Avatar answered Oct 26 '25 23:10

Gazler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!