How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?
When I press the 'refresh' button on my browser, it seems that $_POST
variable is preserved across the refresh.
If I want to delete the contents of $_POST
what should I do? Using unset
for the fields of $_POST
did not help.
Help? Thanks!
Solution 1:
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.
Solution 2:
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;
}
?>
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.
Solution 3:
Simple PHP solution to this:
if (isset($_POST['aaa'])){
echo '
<script type="text/javascript">
location.reload();
</script>';
}
As the page is reloaded it will update on screen the new data and clear the $_POST ;)
Solution 4:
this is a common question here.
Here's a link to a similar question. You can see my answer there. Why POST['submit'] is set when I reload?
The basic answer is to look into post/redirect/get, but since it is easier to see by example, just check the link above.
Solution 5:
My usual technique for this is:
<?php
if ($_POST) {
$errors = validate_post($_POST);
if ($!errors) {
take_action($_POST);
// This is it (you may want to pass some additional parameters to generate visual feedback later):
header('Location: ?');
exit;
}
}
?>