Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Race Conditions in PHP on Submit: Please do not click submit more than once!

Tags:

php

A while back, online apps used to say, "do not click submit more than once." That's gone now, right? How do you guard against that in, say, PHP?

One solution I'm using involves putting a variable in the Session, so you cannot submit to a page more than once every 10 seconds. That way the database work will have completed so the normal checks can take place. Obviously, this feels like a hack and probably is.

Edit: Thanks everybody for the Javascript solution. That's fine, but it is a bit of work. 1) It's an input type=image and 2) The submit has to keep firing until the Spry stuff says it's okay. This edit is just me complaining, basically, since I imagine that after looking at the Spry stuff I'll be able to figure it out.

Edit: Not that anyone will be integrating with the Spry stuff, but here's my final code using Prototype for the document.getElementByid. Comments welcome!

function onSubmitClick() {
    var allValid = true;
    var queue = Spry.Widget.Form.onSubmitWidgetQueue; 
    for (var i=0;i<queue.length; i++) {
        if (!queue[i].validate()) {
            allValid = false;
            break;
        }
    }

    if (allValid) {
        $("theSubmitButton").disabled = true;
        $("form").submit();
    }
}

For some reason, the second form submit was necessary...

like image 512
Dan Rosenstark Avatar asked Jan 05 '09 23:01

Dan Rosenstark


1 Answers

You should do both client- and server-side protections.

Client side - disable button e.g. by jquery as cletus has described.

Server side - put a token in the form. If there are two submissions with the same token, ignore the latter. Using this approach, you are protected against CSRF.

like image 73
ya23 Avatar answered Oct 08 '22 02:10

ya23