PHP: Repost Prevention on Refresh (F5)

After processing the data posted via a form with PHP, if the visitor accidentally or intentionally refreshes the page, he/she will be asked “Do you want to send the same data again?” A warning window may appear. There are many ways to get rid of this.

Usually the preferred method is to redirect the data to a different page after processing it. In some cases, you may not want to redirect to another page or refresh the page in PHP. That’s what I think is healthy.

You can remove this warning with the following snippet (by removing session_start() if it has been run before) and prevent users from posting the same data again.

session_start();
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {       
  $_SESSION['postdata'] = $_POST;
  header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']); exit;
}

if( isset($_SESSION['postdata'])) { 
  $_POST = $_SESSION['postdata'];      
  unset($_SESSION['postdata']); 
}

Leave a Reply

Your email address will not be published. Required fields are marked *