【问题标题】:Modifying / Adding extra stuff to PDO bindParam()?修改/添加额外的东西到 PDO bindParam()?
【发布时间】:2016-07-19 11:26:14
【问题描述】:

有没有人知道是否有一种干净的方式(或任何方式)来改变 PDO 的 bindParam?

我们正在为我们的网站实施额外的安全措施(输入过滤器),到目前为止,将其添加到我们拥有的每个网站的最佳方式似乎是有效的(我们拥有的每个网站都不同,但他们拥有的东西共同点是他们都使用 PDO)会以某种方式使 PDO bindParam 在其参数上调用我们的函数,以便对 bindParam 中的每个输入进行适当的过滤。

谢谢!

【问题讨论】:

  • 我感觉你过滤错误。你具体在做什么?
  • 首先让我说这是一个绝对可怕的想法,你不应该这样做,但是runkit 可用于覆盖核心 PHP 函数。再次,可怕的想法。话虽如此,这里显而易见的选择是重构您进行过滤的方式。
  • 不需要runkit。只需扩展PDOStatement。但是,是的,OP 做错了什么。
  • 顺便说一句,仍然需要更改代码:)
  • 可能XY Problem

标签: php mysql pdo php-5.4


【解决方案1】:

通过扩展 PDO 类解决了这个问题:

class CustomDBConnection {

    private static $conn;

    // either create a new connection or return an existing one
    public static function getInstance() {
        if (self::$conn == null) {
            global $db_hostname, $db_database, $db_username, $db_password; // probably better to store these within this class but this was quicker
            self::$conn = new CustomPDO("mysql:host=$db_hostname;dbname=$db_database;charset=utf8", $db_username, $db_password, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
        }

        return self::$conn;
    }
}

class CustomPDO extends PDO {

    public function __construct($dsn, $username = null, $password = null, $driver_options = array()) {

        parent::__construct($dsn, $username, $password, $driver_options);

        // Attach customised PDOStatement class
        $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('CustomPDOStatement', array($this)));
    }
}

class CustomPDOStatement extends PDOStatement {

    private $conn;

    protected function __construct($conn) {
        $this->conn = $conn; // this is most likely useless at this moment
    }

    public function bindParam($parameter, &$variable, $data_type = PDO::PARAM_STR, $length = null, $driver_options = null) {
        $variable = InputProtection::detachEvilHTML($variable);

        parent::bindParam($parameter, $variable, $data_type, $length, $driver_options);
    }

    public function bindValue($parameter, $value, $data_type = PDO::PARAM_STR) {
        $value = InputProtection::detachEvilHTML($value);

        parent::bindValue($parameter, $value, $data_type);
    }
}

所以我现在基本上使用$db = CustomDBConnection::getInstance(); 而不是$db = new PDO(.......);

【讨论】:

    猜你喜欢
    • 2015-05-31
    • 2010-09-05
    • 2017-11-27
    • 2023-01-30
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2011-04-13
    • 2022-06-11
    相关资源
    最近更新 更多