Redirect After Post, But Not On Failure
Post/Redirect/Get (PRG) is a great practice, but don’t use it when the post is a failure. Here are some reasons:
- If post failed because of non-validation issue, e.g. if “try again later” was the result, then the client only has to refresh the page to submit the post again.
- It’s more efficient (greener) and easier to develop: if redirecting even on failure, then you must store the post data in the session and pull it back out to refill the form (or require the user to fill out the entire form again).
Implementation examples follow:
Pseudocode:
if request is post
if data is valid
process data
redirect and return
load view
PHP Example:
<?php
$errors = array();
$data = array(
'name' => '',
'email' => '',
'password' => '',
'password_confirmation' => '',
);
if (!empty($_POST))
{
// request is POST
$data = $_POST + $data;
// validate data (some of this could be moved to the model)
if (empty($data['name']))
{
$errors['name'] = 'Name is required.';
}
if (empty($data['email']))
{
$errors['email'] = 'E-mail is required.';
}
else if (!Validator::isEmailValid($data['email']))
{
$errors['email'] = 'Please enter a valid e-mail address.';
}
if (empty($data['password']))
{
$errors['password'] = 'Please enter a password.';
}
else if ($data['password'] != $data['password_confirmation'])
{
$errors['password'] = 'Passwords do not match.';
}
if (empty($errors))
{
// process data
$account = new Account();
$account->setName($data['name']);
$account->setEmail($data['email']);
$account->setPassword($data['password']);
$account->save();
// redirect and return
$this->redirect('/');
exit();
}
}
// load view
?>