在Laravel中,如何过滤中间件中所有输入的reuqest对象上的字符串?

问题描述

让我详细解释

我想保护我的查询字符串变量作为注入字符串

URL:http://domainname.com/report?start_date=';选择; -

就像在上面的URL中看到的那样,有一些意外的字符串,我想在使用$ request对象将其获取到控制器上的同时对其进行修整

例如:$ start_date = $ request-> get('start_date');

然后我将这个$ start_date直接用于查询 我不想使用验证器,我该如何使用中间件为所有输入(不仅限于start_date)进行验证 提取所有输入和剥离标签删除特殊字符

解决方法

您已经拥有称为TrimStrings的Middlware,通常位于以下位置

/app/Http/Middlware/TrimStrings.php

之后,您可以覆盖函数transform,使其看起来像这样

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;

class TrimStrings extends Middleware
{
    /**
     * The names of the attributes that should not be trimmed.
     *
     * @var array
     */
    protected $except = [
        'password','password_confirmation',];
    
    protected function transform($key,$value)
    {
        $value = htmlentities($value);
        $value = htmlspecialchars($value);
        $value = $this->myCustomFilteringFunction(); // You can add your function and to whatever you want
        
        if (in_array($key,$this->except,true)) {
            return $value;
        }

        return is_string($value) ? trim($value) : $value;
    }
}

不需要重新发明轮子,这种中间件方法transform将在每个领域被调用。因此,一切都得到了照顾。只需添加您的过滤规则即可。