← PHP / Laravel · 目次

PHP-003 / 中級

orderBy への利用者入力カラム名の渡し

A03:2021 Injection · CWE-89 SQL Injection

なぜ問題になるのか?

カラム名などの識別子はバインドパラメータで処理できないため、許可リストが必要です。サブクエリ注入も可能です。

修正方法

php
$allowed = ['created_at', 'title'];
$sort = in_array($request->sort, $allowed, true) ? $request->sort : 'created_at';
$posts = Post::orderBy($sort, 'desc')->get();

参考資料