-1 php sql sql-injection
我是初学者。我写了这篇文章,我被告知我的 find() 方法存在安全漏洞。我认为我的 queryType 方法的 if else 阻止了 Sql 注入尝试。
public function queryType(string $sql, array $attributes = null)
{
## instance of Database singleton
$this->Database = Database::getInstance();
if($attributes !== null) {
## if attr, prepared request
$query = $this->Database->prepare($sql);
$query->execute($attributes);
return $query;
}else{
## else, simple request
return $this->Database->query($sql);
}
}
## SECURITY ISSUE /!\ ?? queryType if/else doesn't prevent ??
public function find(int $id)
{
return $this->queryType("SELECT * FROM {$this->table} WHERE id = $id")->fetch();
}
Run Code Online (Sandbox Code Playgroud)
我该如何解决它?
代码仅在您实际使用时才提供安全性。因为您没有传递任何参数,所以显示的查询将落入“其他,简单请求”的情况,因此queryType 支持参数的事实是无关紧要的。这就像在门上安装一个沉重的铁插销,但永远不要将其滑入到位 - 它不会将任何人拒之门外。
在这种情况下,$id保证为 int,因此风险很小,但您应该养成始终使用参数的习惯:$this->queryType("SELECT * FROM {$this->table} WHERE id = ?", [$id])
但是,您还有另一个不能作为参数的动态部分:$this->table如果用户有任何方法可以选择该值,那么这将是一个巨大的安全漏洞。如果这是针对某种“ORM”,其中每个表都有一个类,那么使用类常量可能是明智的(例如$tableName = static::TABLE_NAME;);这样,子类可以定义一个值,但它永远不会在运行时计算,因此您不会意外地将用户控制的值放入其中。