php - 防止SQL注入(inject): Do I need to escape input before binding values into a PDO query

标签 php mysql pdo

  1. 在下面的场景中,$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();
    
  2. 我看到有些人在插入查询之前不会转义输入,但他们会在回显数据之前转义数据。他们为什么要这样做?

    $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;
    
  3. 查询前后是否需要使用htmentities()?

最佳答案

如果您使用准备好的查询,则无需转义/转换 HTML 来避免 SQL 注入(inject)。至于何时需要使用 htmlentitieshtmlspecialchars,如果您将用户提供的数据输出到网页,则需要使用它们。不这样做会使您容易受到XSS的影响。 (跨站脚本)注入(inject),即。页面加载时在浏览器中执行的恶意 JavaScript。推荐阅读:XSS Prevention Cheat SheetPHP 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/

相关文章:

Mysql连接不同的表

php - Laravel/Eloquent - 无法执行原始查询

php - MongoDB:ObjectId 到字符串

php - 如何过滤多个类别并显示它的帖子/文章 PHP

php - 获取变量数组的数据库数据

PHP PDO : Array in Update SQL WHERE IN () clause

php - 我收到此错误代码 : Invalid argument supplied for foreach()

php - 发生事情时如何使用php脚本,ajax?

php - 向 PHP MYSQL 函数添加 If/else 错误/成功消息

php - 使用 Imagick 创建 PDF 缩略图并写入文件