在使用原始SQL时,Laravel会自然地阻止SQL注入吗?

时间:2018-05-15 08:17:42

标签: sql laravel sql-injection

我知道每个人都在使用 public void increasePriority(T value, int oldPriority, int newPriority) throws PriorityQueueException { if (c.compare(oldPriority, newPriority) > 0) throw new PriorityQueueException("The new priority is lower than the current one"); int i = getSize() - 1; while (i > 0 && !(queue.get(i).getPriority() == oldPriority && queue.get(i).getValue() == value)) { i = getParent(i); } if (i == 0) throw new PriorityQueueException("Element (" + value + "," + oldPriority +") doesn't exits in the queue"); queue.get(i).setPriority(newPriority); while (i > 0 && c.compare(queue.get(i).getPriority(), queue.get(getParent(i)).getPriority()) > 0) { swap(i, getParent(i)); i = getParent(i); } }来执行原始sql。

我自己使用以下内容:

DB::raw()

Laravel是否已经提供了针对SQL注入的防御,或者我仍然需要转义我的变量?

1 个答案:

答案 0 :(得分:1)

是laravel为sql注入提供防御。

这是因为由于查询构建器在后台使用PDO,我们知道有一种方法可以将参数绑定到查询中,因此它将清理绑定变量。

现在,正如您所见,使用例如DB::select()方法在查询构建器中完成任意(原始)查询。让我们看看select()中的Illuminate\Database\Connection方法,看看它是否有办法绑定我们的参数。让我们深入研究它:

      public function select($query, $bindings = [], $useReadPdo = true)
{
    return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {
        if ($this->pretending()) {
            return [];
        }

        // For select statements, we'll simply execute the query and return an array
        // of the database result set. Each element in the array will be a single
        // row from the database table, and will either be an array or objects.
        $statement = $this->prepared($this->getPdoForSelect($useReadPdo)
                          ->prepare($query));

        $this->bindValues($statement, $this->prepareBindings($bindings));

        $statement->execute();

        return $statement->fetchAll();
    });
}

您的查询可能如下所示:

    $someVariable = Input::get("some_variable");
    DB::select("SELECT * FROM some_table WHERE some_col = :somevariable", array(
       'somevariable' => $someVariable,
     ));