Laravel/PHP multiple form submissions (multiple click on submit button)

假装没事ソ 提交于 2020-01-14 04:08:26

问题


I've some problems due to multiple form submissions. I'm using laravel as framework and creating a browsergame (I know, there are millions) just for fun.

I've a page for buildings with a button "Construct" which is in a form (method="post").

If I hold Enter for 4-5 seconds many request will be fired and the user can create many records in the database.

I don't want an only client side fix like

$(document).on('submit', 'form', function() {
    $(this).find('button:submit, input:submit').attr('disabled', 'disabled);
});

Because never trust the client.

Is someone here with a solution (maybe with laravel)?

Thanks in advance.

Best regards.


回答1:


You can control it in server side using csrf token. Your form will have a token for preventing cross-site request forgery, and you can access this token in your controller to identify the client uniquely. When a request coming to the controller you can check whether the client sending the request first time or not. If it is not first time you can return back. Example:-

public function construct(Request $request){
     $token = $request->_token;
     //check weather the token already exists or not, using db or session
     if(exists){
         return;
     }
}



回答2:


"Generate a random token. Put token in session. Put token in form as hidden field. On submit if token received is equal to the one in session do all the stuff on database and delete token from session."

"Using middleware for route group (laravel.com/docs/5.6/routing#route-group-middleware) you can View::share (laravel.com/docs/5.6/views#sharing-data-with-all-views) a random token and save on session."

Thanks @assistbss



来源:https://stackoverflow.com/questions/49454614/laravel-php-multiple-form-submissions-multiple-click-on-submit-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!