Prevent the launch of scripts entered by the user on a web page

My application has a comment box. If someone adds a comment like

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

then a warning appears when loading this page.

Is there a way to prevent this?

+3


source to share


2 answers


There are several ways to solve this problem, but since you did not indicate which of the existing technologies you are using, it is difficult to provide anything other than rough answers.

Also, you haven't specified whether you want to enable or disable the ability to enter normal HTML into the field.

Method 1:

Sanitize the input along the way. When you are hosting something on the server, find the script tags and remove them.

This is actually much more complicated than you might expect.

Method 2:



Reset the data on the way back to the server. In PHP there is a function called htmlentities

that will turn all HTML into which literally what has been printed is displayed.

The words <script>alert("hello")</script>

will appear on your page.

Method 3

White list

This is far beyond one post, and you really need to know your internal system, but it is possible to allow some HTML characters while disallowing others.

This is insanely difficult to get it right, and your really best bet is to use a library package that has been very well tested.

+2


source


You should treat user input as plain text and not HTML. By properly escaping HTML objects, you can render what looks like valid HTML text without the browser trying to execute it. This is good practice in general, for your client code as well as any user supplied values ​​passed to your internal content. The problems that come with this are commonly referred to as script injection or cross-site scripting.



Practically on the client side, this is pretty straightforward since you are using jQuery. When updating the DOM based on user input, rely on text

instead . You can see a simple example of the difference in the jsFiddle . html

+1


source







All Articles