防止表单中的 php 注入(如果用户将 php 代码提交到表单中)
在联系表单中,如果有人在文本框中输入以下内容:
<?php echo 'hi'; ?>
我看到服务器由于错误而不会执行它。相反,我希望它以某种方式将其转义为纯文本并正确显示。我见过其他网站能够做到这一点。我原本以为这个问题可以通过addslashes()函数来解决,但这似乎不起作用。
谢谢, 菲尔
In a contact form, if someone enters the following into the textbox:
<?php echo 'hi'; ?>
I see that the server will not execute it because of an error. What I would like it to do is instead, somehow escape it into plain text and display it correctly. I have seen other sites been able to do this. I originally thought this could be solved by the addslashes() function, but that doesn't seem to work.
Thanks,
Phil
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不可以。请使用
htmlspecialchars
代替。不要使用addslashes
。更具体地说,
addslashes
直接转义'
、"
和\
以及NUL< 的所有实例。 /code>。它的目的是防止SQL注入,但它在适当的安全性方面没有真正的用处。 。
你想要的是阻止浏览器 按原样解释标签(这与防止 SQL 注入完全不同),例如,如果我想谈论
元素,那么不应简单地按字面发送该字符串,从而导致启动。一个实际的脚本(可能导致跨站脚本),但有些字符,尤其是
<
和>
需要编码为 HTML 实体,以便它们显示为尖括号 (对于&
也是如此,否则将被解释为 HTML 实体的开头)。在您的情况下,
htmlspecialchars
之后的输出将如下所示:No. Use
htmlspecialchars
instead. Don't useaddslashes
.To be more specific,
addslashes
bluntly escapes all instances of'
,"
and\
andNUL
. It was meant to prevent SQL injection, but it has no real use in proper security measures.What you want is preventing the browser to interpret tags as is (and that's entirely different from preventing SQL injections). For instance, if I want to talk about
<script>
elements, SO shouldn't simply send that string literally, causing to start an actual script (that can lead to Cross-site scripting), but some characters, especially<
and>
, need to be encoded as HTML entities so they're shown as angle brackets (the same is true for&
, that otherwise would be interpreted as the start of an HTML entity).In your case, output after
htmlspecialchars
would look like:在输出用户提供的任何内容之前使用 htmlspecialchars 。但在这种情况下,还要确保您不执行用户输入的任何内容。不要使用 eval、include 或 require。如果将用户数据保存到文件中,请使用 readfile 或 file_get_contents+htmlspecialchars 而不是 include/require。如果你使用的是eval,请将其更改为echo等。
Use htmlspecialchars before outputing anything provided by the user. But in this case, also make sure that you do not execute anything the user inputs. Do not use eval, include or require. If you save the user data to a file, use readfile or file_get_contents+htmlspecialchars instead of include/require. If you're using eval, change it into echo and so on.