如何保护表单?
我正在阅读一篇有关表单安全性的文章,因为我有一个用户可以在其中添加消息的表单。
我读到最好使用 strip_tags()
、htmlspecialchars()
和 nl2br()
。在其他地方据说使用 html_entity_decode()
。
我的页面中有这段代码,它接受用户输入,
<?php
$topicmessage = check_input($_POST['message']); //protect against SQLinjection
$topicmessage = strip_tags($topicmessage, "<p><a><span>");
$topicmessage = htmlspecialchars($topicmessage);
$topicmessage = nl2br($topicmessage);
?>
但是当我回显该消息时,它全部在一行上,并且似乎中断已被 strip_tags
删除,并且没有被 放回>nl2br()
。
对我来说,这是有道理的,因为如果中断已被删除,它如何知道将其放回何处(或者确实如此)?
不管怎样,我正在寻找一种方法来保护我的表单,使其不被用来尝试破解网站,例如在表单中使用 javascript。
I was reading an article about form security because I have a form in which a user can add messages.
I read that it was best to use strip_tags()
, htmlspecialchars()
and nl2br()
. Somewhere else it is being said to use html_entity_decode()
.
I have this code in my page which takes the user input
<?php
$topicmessage = check_input($_POST['message']); //protect against SQLinjection
$topicmessage = strip_tags($topicmessage, "<p><a><span>");
$topicmessage = htmlspecialchars($topicmessage);
$topicmessage = nl2br($topicmessage);
?>
but when i echo the message, it's all on one line and it appears that the breaks have been removed by the strip_tags
and not put back by nl2br()
.
To me, that makes sense why it does that, because if the break has been removed, how does it know where to put it back (or does it)?
Anyway, i'm looking for a way where i can protect my form for being used to try and hack the site like using javascript in the form.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您有 2 个选择:
绝对不允许 HTML。使用
strip_tags()
和 NO 允许的标签,或htmlspecialchars()
来转义其中可能存在的任何标签。允许 HTML,但您需要清理 HTML。这是不能使用
strip_tags
可以做到的事情。使用库(例如 HTMLPurifier)...You have 2 choices:
Allow absolutely no HTML. Use
strip_tags()
with NO allowed tags, orhtmlspecialchars()
to escape any tags that may be in there.Allow HTML, but you need to sanitize the HTML. This is NOT something you can do with
strip_tags
. Use a library (Such as HTMLPurifier)...你只需要在打印表单内容之前使用 htmlspecialchars ,并在发布到 SQL 之前使用 mysql_real_escape (在打印之前不需要它),你应该没问题。
以您的方式添加标签是非常危险的,您需要具有有限属性的允许标签的简短列表 - 这不是您可以在 1 行中完成的事情。您可能想研究 HTML 规范化器,例如 Tidy。
You just need htmlspecialchars before printing form content, and mysql_real_escape before posting into SQL(you don't need it before printing), and you should be good.
Doing your way of stipping tags is very dangerous, you need short list of allowed tags with limited attributes - this is not something you can do in 1 line. You might want to look into HTML normalizers, like Tidy.
不相关但很重要:
Unrelated but important: