Preventing form re-submission with HTTP 303 redirects

After processing form data with a server side language like Ruby, Python, or PHP, it’s common to show some sort of confirmation to the user. Many applications will use an HTTP redirect to send the user to a different URL for the confirmation, in an attempt to prevent the browser from resubmitting the form if the user hits “refresh” or “back”.

This is a good idea, but unfortunately most web programming languages, including Ruby, Python, and PHP, default to an HTTP 302 (Temporarily Moved) redirect. This tells the web browser “the URL you just submitted data to has temporarily moved; you can now find it here.” Some browsers will cache this redirect, causing the form to be resubmitted on a page refresh, despite the different URL. No bueno.

Luckily it’s the little-known 303 redirect to the rescue. From the HTTP/1.1 spec:

10.3.4 303 See Other

The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource. This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.

To use the 303 redirect, just issue a “HTTP/1.1 303 See Other” header followed by a typical “location” header. In PHP, it looks like this:

header(‘HTTP/1.1 303 See Other’);
header(‘location: http://www.mysite.com/some-url/’)

Unlike the 302 redirect, the 303 redirect never gets cached, so users can refresh your form confirmation page with aplomb.

  1. torrent-sites reblogged this from jonthornton
  2. glidepro reblogged this from jonthornton and added:
    header(‘HTTP/1.1 303
  3. datafetish reblogged this from jonthornton
  4. terrcin reblogged this from jonthornton
  5. ilikeprivacy reblogged this from jonthornton
  6. jonthornton posted this