Reputation: 746
I have a textbox and submit button which posts the content and a reply to the HTML page. Is there any way (other than checking if the string's substring at the beginning is
<h1>,<h2>,<h3>...,<script>,<style>,etc.
to see if a string will be formatted differently when it is posted on the page, in order to prevent code injection?
Thanks
-Zach
Upvotes: 0
Views: 165
Reputation: 25605
When you display user data, you should correctly encode it as html. In javascript, use document.createTextNode(userData)
and append that node instead of using innerHTML. In PHP, use htmlentities
.
If the user is allowed to use any html or formatting, you should do them with a strict whitelist of allowed tags and attributes, and encode everything else as plain text.
So, even if the user did enter <h1>stuff</h1>
, when that's properly encoded, it will come out as <h1>test</h1>
instead of html, which won't be vulnerable to javascript injection.
Upvotes: 1