阻止用户输入的脚本在网页中运行 [英] Prevent user-entered scripts from running in webpage

查看:99
本文介绍了阻止用户输入的脚本在网页中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,有一个注释框.如果有人输入

In my application, there is a comment box. If someone enters a comment like

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

然后,当我加载该页面时会出现警报.

then an alert appears when I load that page.

反正有防止这种情况发生吗?

Is there anyway to prevent this?

推荐答案

有几种方法可以解决此问题,但是由于您没有提到正在使用的后端技术,因此除了给出大致答案外,很难给出其他任何答案.

There are several ways to address this, but since you haven't mentioned which back-end technology you are using, it is hard to give anything but rough answers.

此外,您还没有提及是否要允许或拒绝在框中输入常规 HTML的功能.

Also, you haven't mentioned if you want to allow, or deny, the ability to enter regular HTML in the box.

方法1:

清理输入中的输入.在服务器上接受某些内容时,查找脚本标记并将其删除.

Sanitize inputs on the way in. When you accept something at the server, look for the script tags and remove them.

要想正确,实际上要困难得多.

This is actually far more difficult to get right then might be expected.

方法2:

在返回服务器的途中转义数据.在PHP中,有一个名为 htmlentities ,它将把所有HTML转换成实际按键入内容呈现的HTML.

Escape the data on the way back down to the server. In PHP there is a function called htmlentities which will turn all HTML into which renders as literally what was typed.

<script>alert("hello")</script>字样会出现在您的页面上.

The words <script>alert("hello")</script> would appear on your page.

方法3

白名单

这远远超出了单个帖子的答案,并且确实需要了解您的后端系统,但是可以允许一些 HTML字符,而不允许其他字符.

This is far beyond the answer of a single post and really required knowing your back-end system, but it is possible to allow some HTML characters with disallowing others.

这很难正确地解决,您最好使用经过充分测试的库包.

This is insanely difficult to get right and you really are best using a library package that has been very well tested.

这篇关于阻止用户输入的脚本在网页中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆