Reputation: 4045
I know that it might stupid but how to escape user input when I show it in a form. I do not mean any output, but especially in the form inputs. Like for example if I have input tag and put the user text in the value.
<input type="text" value="'test' "test" <script>alert('hacked');</script>" />
When I leave it like that it appears correctly
'test' "test" <script>alert('hacked');</script>
no XSS happens, but I do not feel secure cause with other code it could break eventually. Is there something like a browser build-in methods for preventing XSS when putting data in the form or I am missing something?
Edit: I did not say the entire story. Sorry about that. When I use htmlentities
or htmlspecialchars
I get the escaped data which I do not want. I see this in the input, which is not what was entered :(
'test' "test" <script>alert('hacked');</script>
I want to prevent XSS and to show the content without changing it at the same time. Is it possible in this case.
Upvotes: 3
Views: 1693
Reputation: 700302
You should HTML encode the text, so that it ends up like this:
<input type="text" value="'test' "test" <script>alert('hacked');</script>" />
You should use the server language to do this. There is no built in support for this in Javascript, so you would have to build a function for that yourself.
In ASP.NET MVC for example it could look like this:
<input type="text" value="<%= Server.HtmlEncode(Model.UserInput) %>" />
MVC 2 also has the <%: %>
tag that automatically encodes the text:
<input type="text" value="<%: Model.UserInput %>" />
Examine the source of the page in the browser to see what the result is.
It looks like you are escaping the text twice, so that for example "
is escaped into "
and then into &quot;
.
Upvotes: 3
Reputation: 9496
Since the quote mark is used to break out of the input attribute, simply replace all quote marks with "
Upvotes: 0
Reputation: 1430
In PHP, use htmlspecialchars()
to escape XSS characters in any GET or POST content (for example, if your data is called $_POST['data']
, escape that like this: $variable = htmlspecialchars($_POST['data']);
). Also, if you're using a database use addslashes()
to escape quotes and apostrophes.
Hope this helps.
Upvotes: 2
Reputation: 601
How are you putting the user text? If you have control, from the server side all languages support encoding the output prior to rendering it on the browser.
As long as you sanitize the output. You can basically allow the user to enter anything that they wish. Then when displaying the content, you just need to encode it so that the browser will not execute it. This can be done from any language PHP, JScript, ASP, VB, C#, etc...
Upvotes: 0