3

I have an edit-form page to edit my website posts. It uses post method to the same page. If the form is compiled correctly shows up a congrats message.

The problem:

When users hit the refresh button the script tries to repost the data again to page. Is there a way to avoid this?

thanks

Luca

Jon
  • 428,835
  • 81
  • 738
  • 806
luca
  • 36,606
  • 27
  • 86
  • 125

4 Answers4

9

The general outline of the PRG pattern is this:

if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
     /// do your magic

     $_SESSION['error'] = "Thanks for your message!";

     // this should be the full URL per spec, but "/yourscript.php" will work
     $myurl = ...;

     header("Location: $myurl");
     header("HTTP/1.1 303 See Other");
     die("redirecting");
}

if ( isset($_SESSION['error']) )
{
     print "The result of your submission: ".$_SESSION['error'];
     unset($_SESSION['error']);
}
mvds
  • 45,755
  • 8
  • 102
  • 111
1

You need to use the PRG pattern.

Jon
  • 428,835
  • 81
  • 738
  • 806
1

You should use the PRG pattern already mentioned above! Just for completeness I add the possibility of using javascript history.replaceState if your forms depend on js (e.g. noscript should invalidate the form or something similar...).

<script>
  window.history.replaceState({}, '#no-reload');
</script>
webfan
  • 11
  • 2
0

This is called the Post/Redirect/Get pattern. You do this by responding to a POST request with a 302/303 Redirect, which prevents that troublesome behavior on the client.

You can read more about this in the link I posted above.

Filipe
  • 281
  • 1
  • 14