【问题标题】:Laravel Prevent Form from Re submittingLaravel 防止表单重新提交
【发布时间】:2019-03-28 18:54:04
【问题描述】:

我有一种在数据库中添加专辑的形式

 {!! Form::open(['method' => 'POST', 'route' => ['admin.album.store'], 'enctype' => 'multipart/form-data', 'id' => 'CreateAlbumForm']) !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">

// other fields

{!! Form::submit(trans('global.app_save'), ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}

它运行良好。

我需要的是防止用户多次单击提交按钮。我知道使用 jquery(点击时禁用提交按钮) 是可能的。

但我想在用户未启用 javascript 时使用 csrf 保护(服务器端)

经过大量搜索,我找到了以下解决方案:

我的尝试

VerifyCsrfToken.php中添加下方函数

protected function tokensMatch($request)
{
    $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');

    if (!$token && $header = $request->header('X-XSRF-TOKEN')) {
        $token = $this->encrypter->decrypt($header);
    }

    $tokensMatch = ($request->session()->token() == $token) ? TRUE : FALSE;

    if($tokensMatch) $request->session()->regenerateToken();

    return $tokensMatch;
}

并在文件app\Http\Requests\FormRequest.php中的$dontFlash数组中添加_token

protected $dontFlash = ['password', 'password_confirmation', '_token'];

它给了我令牌不匹配错误但是当我点击提交按钮超过 2 次时。并且记录被插入 2 次,这是不受欢迎的行为。

它应该在第二次尝试同时提交时给我错误。

简而言之,我需要的是,如果用户单次单击提交按钮,它应该插入记录。如果他多次点击提交,就会出现 TokenMismatch 错误。

【问题讨论】:

  • 为什么不添加一个 onclick 方法来禁用提交时的表单,然后在表单上使用验证来防止它被插入到数据库中?在专辑数据上使用唯一性,例如 laravel.com/docs/5.7/…
  • @rchatburn 我想在服务器端做。我使用了unique,因此按照预期的行为,它将返回错误消息为this is already added,但我不想显示该错误消息,我只想添加单个记录并将用户重定向到列表。

标签: php laravel laravel-5 csrf-protection


【解决方案1】:

You could set a token when you serve the form and check that against the database. When you submit the form, the token is checked and you can't submit it any more. Of course, it is still a good idea to do it front-end too as it is more visual for the user.

https://laracasts.com/discuss/channels/laravel/stopping-multiple-form-submission

只是搜索相关答案并找到了这个。希望它会在某种程度上有所帮助。

【讨论】:

  • 我认为只会在csrf令牌保护中进行一些配置。当我在隐藏字段中传递 csrf 令牌时。这也是有效的,但它仍然允许点击 2 次。我不知道怎么做。它不应该允许第二次请求
猜你喜欢
  • 2013-07-24
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 2018-03-18
  • 2012-04-05
相关资源
最近更新 更多