Escaping ampersands entered by users through text fields?

Like almost all applications today, I have users who enter a variety of information through standard text inputs. My application is powered by Rails.

It's not easy to avoid the ampersands that I include as part of my site copy, etc. But how can I avoid the ampersand that is dynamically entered by the user? This is currently breaking my authentication.

+2


source to share


1 answer


When displaying values, you need to replace certain characters with HTML entities. These symbols are:

& : &
< : &lt;
> : &gt;
" : &quot;

      

Perhaps there is a function HtmlEncode you can use to do this, otherwise you can use simple string operations. Pseudocode:

output replace(replace(replace(replace(text, "&", "&amp"), "<", "&lt;"), ">", "&gt;", """", "&quot;")

      



Edit:
I found that you can use the html_escape () function:

<%=html_escape @text%>

      

Or short:

<%=h @text%>

      

+6


source







All Articles