49

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!

Navneet
  • 9,590
  • 11
  • 34
  • 51
  • That's a browser problem. Try not to hit *Resend form data* when your browser prompts you. – Blender Dec 01 '11 at 02:26
  • 1
    After the form gets submitted and once you've read the POST data, redirect to another page. Then, if the use refreshes that page, the POST data won't get reattached. – Casey Chu Dec 01 '11 at 02:30
  • 1
    @blender I wouldn't say it's a "problem" since it is the functionality of all browsers. Saying so is like saying the back button is a problem. – Kai Qing Dec 01 '11 at 02:33
  • @KaiQing: Well, it's problematic for the OP. – Blender Dec 01 '11 at 02:34

23 Answers23

42

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.

Brandon
  • 16,382
  • 12
  • 55
  • 88
burntblark
  • 1,680
  • 1
  • 15
  • 25
27

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; ?>
Peter
  • 8,776
  • 6
  • 62
  • 95
  • where should we redirect to in header("Location: ".$_SERVER['PHP_SELF']); ? The file with the form ? – MarcoZen Jul 04 '17 at 13:59
  • @MarcoZen To the file that handles your form. In many cases the same file that contains your form. – Peter Jul 05 '17 at 07:57
  • Say i start at a login form, at submit - we direct to a page that processes the POST data ( in this case we capture via SESSION[postdata] and then we redirect them back to the login form ? Huh ? If the login credentials are correct - shouldn't they be directed to the approved page / home page.php etc ? Pls correct me. – MarcoZen Jul 05 '17 at 16:03
  • I would like to add that i had a problem because I only used `header()` without the `exit; `Do not miss out the `edit;` line or it won't work – GeneCode Dec 20 '19 at 03:48
  • you should write an example of how to access the $_SESSION['postdata'] variables now – webs Jan 01 '20 at 20:10
  • worked for me. to access $_SESSION['postdata'] variables example is $name = $_SESSION['postdata']['pupil_name']); – webs Jan 01 '20 at 23:37
  • what is the correct way to access the post data for a form error redirect? – brassmookie May 19 '21 at 19:38
  • @brassmookie You can access the postdate by using for example: `echo $_SESSION['postdata']['name'];` – Peter May 20 '21 at 10:07
  • Fully tested, and this still does the trick in 2021. It even prevents PHP from inserting double records. A great neat little trick! – KJS Sep 02 '21 at 22:41
  • 1
    This is great solution, but instead of "header("Location: ".$_SERVER['PHP_SELF']);" I used header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); and it worked for me. It is the same file that handles and contains the form. – Mirjana Katalina May 10 '22 at 22:45
8

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 ;)

  • i had a php file POSTing to itself FORM data, the way i avoided POST after refresh was to add a header('Location:file.php'); at the end of the php script. Voila, page refreshed right after POST and no data to re-submit (: – brunobliss Nov 17 '16 at 14:18
  • @M H ur right, this ist not clearing the POST Variables... but it's reloading the page so far that you can see the changed result getting a JavaScript Alert, telling you to resend post data to display the entire page... – Kerim Yagmurcu Jan 27 '19 at 03:08
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.

Community
  • 1
  • 1
Kai Qing
  • 18,793
  • 5
  • 39
  • 57
4

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;
   }
}
?>
alx
  • 2,314
  • 2
  • 18
  • 22
3

How about using $_POST = array(), which nullifies the data. The browser will still ask to reload, but there will be no data in the $_POST superglobal.

Otvazhnii
  • 603
  • 5
  • 12
2

This will remove the annoying confirm submission on refresh, the code is self-explanatory:

if (!isset($_SESSION)) {
session_start();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER[REQUEST_URI]);
exit;
}

if (@$_SESSION['postdata']){
$_POST=$_SESSION['postdata'];
unset($_SESSION['postdata']);
}
superbem
  • 441
  • 3
  • 10
2

$_POST should only get populated on POST requests. The browser usually sends GET requests. If you reached a page via POST it usually asks you if it should resend the POST data when you hit refresh. What it does is simply that - sending the POST data again. To PHP that looks like a different request although it semantically contains the same data.

Daff
  • 43,734
  • 9
  • 106
  • 120
  • Yes. I noticed that. Is there a way to override/clear the POST request that is sent while refreshing? – Navneet Dec 01 '11 at 02:30
  • If you are using sessions you can store the last POST there and compare it to the next one you get. – Daff Dec 01 '11 at 02:33
1

The "best" way to do this is Post / Redirect / Get

http://en.wikipedia.org/wiki/Post/Redirect/Get

After the post send a 302 header pointing to the success page

exussum
  • 18,275
  • 8
  • 32
  • 65
1

I had this problem in an online fabric store, where there was a button to order a fabric sample on the product page, if a customer had first ordered a product and then wanted to order a sample of a different colour their previous order would be duplicated, since they never left the page and the POST data was still present.

The only way I could do this reliably was to add a redirecting page (or in my case in WordPress, add action to "parse_request" for a mock url), that redirects back to the referring page.

Javascript:

window.location.href = '/hard-reset-form';

PHP:

header('Location: ' . $_SERVER['HTTP_REFERER']);
die();

This way you are coming back to a new page, all POST data cleared.

1

You can't, this is treated by the browser, not by any programming language. You can use AJAX to make the request or redirect the user to the same (or another) page.

0

Set an intermediate page where you change $_POST variables into $_SESSION. In your actual page, unset them after usage.

You may pass also the initial page URL to set the browser back button.

Hatzegopteryx
  • 600
  • 6
  • 13
0

I have a single form and display where I "add / delete / edit / insert / move" data records using one form and one submit button. What I do first is to check to see if the $_post is set, if not, set it to nothing. then I run through the rest of the code,

then on the actual $_post's I use switches and if / else's based on the data entered and with error checking for each data part required for which function is being used.

After it does whatever to the data, I run a function to clear all the $_post data for each section. you can hit refresh till your blue in the face it won't do anything but refresh the page and display.

So you just need to think logically and make it idiot proof for your users...

0

try

unset($_POST);
unset($_REQUEST);
header('Location: ...');

it worked for me

Matteo
  • 1,673
  • 1
  • 9
  • 4
0

I can see this is an old thread, just thought I'd give my 2cents. Not sure if it would fit every scenario, but this is the method I've been successfully using for a number of years:

session_start();
if($_POST == $_SESSION['oldPOST']) $_POST = array(); else $_SESSION['oldPOST'] = $_POST;

Doesn't really delete POST-ed values from the browser, but as far as your php script below these lines is concerned, there is no more POST variables.

Skip_
  • 1
  • 1
0

This is the most simple way you can do it since you can't clear $_POST data by refreshing the page but by leaving the page and coming back to it again.

This will be on the page you would want to clear $_POST data.

<a class="btn" href="clear_reload.php"> Clear</a> // button to 'clear' data

Now create clear_reload.php.

clear_reload.php:

<?php
header("Location: {$_SERVER['HTTP_REFERER']}");
?>

The "clear" button will direct you to this clear_reload.php page, which will redirect you back to the same page you were at.

0

If somehow, the problem has to do with multiple insertions to your database "on refresh". Check my answer here Unset post variables after form submission. It should help.

Chimdi
  • 303
  • 2
  • 7
0

The Post data can be clear with some tricks.

<?php

if (!isset($_SESSION)) {
    session_start();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_SESSION['postdata'] = $_POST;
    unset($_POST); //unsetting $_POST Array
    header("Location: ".$_SERVER['REQUEST_URI']);//This will let your uri parameters to still exist
    exit;
}
?>
gsm
  • 2,348
  • 17
  • 16
0

In my case I have used the below trick to redirect user to the same page once the $_POST operation has been done.

Example:

if(!empty($_POST['message'])) {
    // do your operation here
    header('Location: '.$_SERVER['PHP_SELF']);
}

It is a very simple trick where we are reloading the page without post variable.

Akash gupta
  • 316
  • 4
  • 4
0

I see this have been answered. However, I ran into the same issue and fixed it by adding the following to the header of the php script.

header("Pragma: no-cache");

Post/Redirect/Get is a good practice no doubt. But even without that, the above should fix the issue.

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
MarlonC
  • 67
  • 6
0

I had a form on my account page which sent data with POST method and I had to store the received data in a database. The data from the database was supposed to be displayed on the webpage but I had to refresh the page after the POST request to display the contents in database. To solve this issue I wrote the following code on account page:

if (isset($_POST['variable'])){
 echo '
 <script type="text/javascript">
  location.href="./index.php?result=success";
 </script>';
}

Then on index.php I refreshed the page and sent the user back to my account page as follows:

if (isset($_GET['result'])) {
    echo'<script>
    //reloads the page  
    location.reload();
    //send user back to account.php
    location.href="./account.php"
   </script>'
}

Shardul Birje
  • 341
  • 5
  • 14
-1

This works for me:

<?if(isset($_POST['oldPost'])):?>
    <form method="post" id="resetPost"></form>
    <script>$("#resetPost").submit()</script>
<?endif?>
MariusH
  • 1
  • 2
-1

You should add the no cache directive to your header:

<?php
header( 'Cache-Control: no-store, no-cache, must-revalidate' ); 
header( 'Cache-Control: post-check=0, pre-check=0', false ); 
header( 'Pragma: no-cache' ); 
?>
Daniel Haviv
  • 1,036
  • 8
  • 16
  • That's a unique one. Is this actually relevant to the question? I've never heard of or seen anyone else suggest this method to avoid reposting form data. Would be kind of neat to know it works. – Kai Qing Dec 01 '11 at 02:45