I am trying to implement proper a Post Redirect Get on a PHP site (question is language agnostic in nature however). I thought about it, and realized that running this code on every request seems to give me the behavior I'm seeking.

if (! empty($_POST))
    header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");

Essentially, if there was a post, redirect to the page we're currently on. This is in the context of a routing framework. I run it before the rest of my code.

Is this bad practice? If so, why? Are there situations when this would cause unexpected behavior? Can this code be improved?

  • You redirect after POST is processed/stored - not before. The point of PRG is to take away this data from browser's sight, so it cant send it again (refresh, double click, back button... etc.). Note that redirect on failure (after post) also need to persist data somehow - otherwise user would have to fill entire form from scratch (imagine sth like that with vague captcha) – shudder Dec 31 '15 at 19:01
  • Behavior that I'm seeing is header only redirects after all code has been run. – Goose Dec 31 '15 at 19:03
  • Ah I see that you don't exit the scipt yet. What page would you display when POST is empty then? – shudder Dec 31 '15 at 19:13
  • The request runs through the router, controller gets data from a model, and view renders it. So essentially the behavior I had before I started implementing the PRG pattern. I've replaced it to the footer, and added an exit, but I'd like to know if there's a practical reason to exit it, or to do it in the header, and anything else that might be wrong with the approach I posted. – Goose Dec 31 '15 at 19:54
  • You might expect empty response body, but the thing is you don't know where to redirect up front. There might be validation error and that needs to send you to form again, when form passes you'll go to success page/item display - and your router would need to struggle to figure it out. Still possible, but unintuitive. Also API should send back success/fail response - redirect is ambigous. – shudder Jan 1 '16 at 2:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.