在下面的场景中,$user_id 是用户输入的字符串。 我想知道是否仍然需要先使用
$email = htmlentities($_POST["email"])
和$name= htmlentities($_POST["name"] 转义字符串)
?$query = "INSERT INTO user ('email','name') VALUES (?,?)"; $this->_query = $this->_pdo->prepare($query); $this->_query->bindValue(1, $email); $this->_query->bindValue(2, $name); $this->_query->execute();
我看到有些人在插入查询之前不会转义输入,但他们会在回显数据之前转义数据。他们为什么要这样做?
$query = "SELECT * FROM users WHERE id = ?"; $this->_query = $this->_pdo->prepare($query); $this->_query->bindValue(1, $user_id); $this->_query->execute(); $data = $this->_query->fetchAll(PDO::FETCH_ASSOC); $output = $data[0]["name"]; $output = htmlentities($output); echo output;
查询前后是否需要使用htmentities()?
最佳答案
如果您使用准备好的查询,则无需转义/转换 HTML 来避免 SQL 注入(inject)。至于何时需要使用 htmlentities
或 htmlspecialchars
,如果您将用户提供的数据输出到网页,则需要使用它们。不这样做会使您容易受到XSS的影响。 (跨站脚本)注入(inject),即。页面加载时在浏览器中执行的恶意 JavaScript。推荐阅读:XSS Prevention Cheat Sheet和 PHP Security Cheat Sheet .
除了预防 SQL 和 XSS 注入(inject)之外,您可能还需要对用户输入进行其他检查,例如在将电子邮件地址、用户名字符等输入数据库之前验证它们。否则,您将面临一些繁琐的数据库清理工作。您可能想查看PHP's filter functions ,删除白名单字符范围之外的所有内容的基本正则表达式等。
关于php - 防止SQL注入(inject): Do I need to escape input before binding values into a PDO query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41211157/