Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent double / duplicate form submissions in CakePHP?

Tags:

php

cakephp

I discovered the Security Component in CakePHP helps to prevent CSRF by adding tokens as hidden values to forms.

What I was wondering is if there was anyway to prevent duplicate form submissions using this Component or some other component/helper?

In previous projects, I used a unique hash saved in a session, which is read then deleted upon submit. A repeated submit would have that same hash and an error would be produced.

thanks

like image 824
bunwich Avatar asked Mar 16 '09 18:03

bunwich


4 Answers

I've puted onClick event that disables the button like this:

<?= $this->Form->button('Salvar', [
                    'value' =>'Submit', 
                    'onClick' => 'form.submit();this.disabled=true'
]) 
?>
like image 121
Kelvin Primo Avatar answered Nov 05 '22 20:11

Kelvin Primo


You could implement the same type of thing in Cake as you've done before.

On submit, set a session variable that marks that form as having been submitted. Make sure to put an expiry time after it (within a few seconds should do the trick). If the session variable is there when you process the form (and you're within that expiration time), then you've got a resubmit, so don't save the form data.

I'd recommend doing this within the save(..) method of your model, so you don't need to worry about adding it in multiple code locations.

like image 25
Travis Leleu Avatar answered Nov 05 '22 22:11

Travis Leleu


There is a feature in CakePHP 2.x in the security component that allows you to choose to either use the same security token till it expires or just once. Place this in your controllers beforeFilter method:

$this->Security->csrfUseOnce = true;

Find more information here

like image 2
DoctorFox Avatar answered Nov 05 '22 21:11

DoctorFox


@DoctorFox has already answered it with csrfUseOnce = true, but this will throw you in blackholes that you still have to manage. So the complete solution for me is :

class YourAppController extends AppController {

    public $helpers = array('Html', 'Form');
    public $components = array('Security');

    public function beforeFilter() {
        $this->Security->csrfUseOnce = true;
        $this->Security->blackHoleCallback = 'blackhole';
    } 

    public function blackhole($type) {
        $this->redirect(array('action' => 'index'));
    }

If there is no redirection, you are still open for double form submission.

Ref : CakePHP security component

like image 2
Eric Lavoie Avatar answered Nov 05 '22 21:11

Eric Lavoie