How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?
The request header contains some POST data. No matter what you do, when you reload the page, the rquest would be sent again.
The simple solution is to redirect to a new (if not the same) page. This pattern is very common in web applications, and is called Post/Redirect/Get. It's typical for all forms to do a POST, then if successful, you should do a redirect.
Try as much as possible to always separate (in different files) your view script (html mostly) from your controller script (business logic and stuff). In this way, you would always post data to a seperate controller script and then redirect back to a view script which when rendered, will contain no POST data in the request header.
To prevent users from refreshing the page or pressing the back button and resubmitting the form I use the following neat little trick.
<?php
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
// This code can be used anywhere you redirect your user to using the header("Location: ...")
if (array_key_exists('postdata', $_SESSION)) {
// Handle your submitted form here using the $_SESSION['postdata'] instead of $_POST
// After using the postdata, don't forget to unset/clear it
unset($_SESSION['postdata']);
}
?>
The POST data is now in a session and users can refresh however much they want. It will no longer have effect on your code.
Use case/example
<!-- Demo after submitting -->
<?php if (array_key_exists('postdata', $_SESSION)): ?>
The name you entered was <?= $_SESSION['postdata']['name']; ?>.
<!-- As specified above, clear the postdata from the session -->
<?php unset($_SESSION['postdata']); ?>
<?php endif; ?>
<!-- Demo form -->
<?php if (!isset($_SESSION['postdata'])): ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name" /><br />
<input type="submit" value="Submit" />
</form>
<?php endif; ?>