Followers

Wednesday 18 December 2013

PHP trick Redirect forms to their originating pages

Redirect forms to their originating pages

When I first started writing PHP, I tended to have forms as two pages. A page with the form on it and the page that processed the form/showed error messages if something went wrong. If there was an error in the data the user entered, I would display the error message and force the user to go back to the previous page to fix it. Nasty. The better solution is to redirect to the same page. 

$errors = array();
$form_submitted = isset($_POST['submit']);
$show_form = true;

if ($form_submitted)
{
  // check for errors.
  // add any error messages to $errors

  if (count($errors) == 0)
  {
    // do SQL magic or whatnot
    $show_form = false;
  }
  else
  {
    echo "The following errors were encountered: <br />".implode("<br />", $errors);
    $show_form = true;
  }
}

if ($show_form)
{
  echo '<form action="this page" method="post"> ... </form>';
}

No comments:

Post a Comment