gpt4 book ai didi

php - 如何防止PHP中的代码注入(inject)攻击?

转载 作者:IT王子 更新时间:2023-10-29 00:39:27 24 4
gpt4 key购买 nike

我有点糊涂了,PHP函数那么多,有的用这个,有的用那个。有些人使用:htmlspecialchars()htmlentities()strip_tags()

哪个是正确的,你们通常使用什么?

这是正确的吗(建议我一个更好的,如果有的话):

$var = mysql_real_escape_string(htmlentities($_POST['username']));

这条线可以防止MySQL注入(inject)和XSS攻击??

顺便说一句,除了XSS攻击和MySQL注入(inject),还有什么需要注意的吗?

编辑

总结:

如果我想向数据库中插入字符串,我不需要使用htmlentities,只需使用mysql_real_escape_string。显示数据的时候,用htmlentities(),你们都是这个意思吗??

总结:

  • mysql_real_escape_string 插入数据库时​​使用
  • htmlentities() 输出数据到网页时使用
  • htmlspecialchars() 什么时候使用?
  • strip_tags() 什么时候使用?
  • addslashes() 什么时候使用?

有人可以填问号吗?

最佳答案

  • mysql_real_escape_string used when insert into database
  • htmlentities() used when outputting data into webpage
  • htmlspecialchars() used when?
  • strip_tags() used when?
  • addslashes() used when?

htmlspecialchars() 什么时候使用?

htmlspecialcharshtmlentities大致相同.区别:字符编码。

两者都对控制字符进行编码,例如 < , > , &等等用于打开标签等htmlentities还编码来自其他语言的字符,如变音符号、欧元符号等。如果您的网站是 UTF,请使用 htmlspecialchars() , 否则使用 htmlentities() .

strip_tags() 什么时候使用?

htmlspecialchars/entities对特殊字符进行编码,以便它们显示但不解释strip_tags删除它们。

在实践中,这取决于您需要做什么。

例如:您编写了一个论坛,并为用户提供了一个文本字段,以便他们可以发布内容。恶意的只是尝试:

pictures of <a href="javascript:void(window.setInterval(function () {window.open('http://evil.example');}, 1000));">kittens</a> here

如果您什么都不做,链接就会显示出来,点击链接的受害者会收到很多弹出窗口。

如果您的输出是 htmlentity/htmlspecialchar,文本将按原样存在。如果你 strip_tag 它,它只是删除标签并显示它:

pictures of kittens here

有时您可能想要混合,在其中留下一些标签,例如 <b> (strip_tags 可以在其中留下某些标签)。这也不安全,所以最好使用一些成熟的库来对抗 XSS。

添加斜线

引用old version of the PHP manual :

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte).

An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. It's highly recommeneded to use DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_string() for PostgreSQL), but if the DBMS you're using does't have an escape function and the DBMS uses \ to escape special chars, you can use this function.

current version措辞不同。

关于php - 如何防止PHP中的代码注入(inject)攻击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1205889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com