51

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!

4
  • That's a browser problem. Try not to hit Resend form data when your browser prompts you. Commented Dec 1, 2011 at 2: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. Commented Dec 1, 2011 at 2: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. Commented Dec 1, 2011 at 2:33
  • @KaiQing: Well, it's problematic for the OP. Commented Dec 1, 2011 at 2:34

23 Answers 23

44

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.

Sign up to request clarification or add additional context in comments.

Comments

28

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

10 Comments

where should we redirect to in header("Location: ".$_SERVER['PHP_SELF']); ? The file with the form ?
@MarcoZen To the file that handles your form. In many cases the same file that contains your form.
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.
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
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.
|
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 ;)

2 Comments

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 (:
@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...
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.

1 Comment

Came here to say the same thing. Use PRG. en.wikipedia.org/wiki/Post/Redirect/Get
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; } } ?> 

Comments

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.

Comments

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.

2 Comments

Yes. I noticed that. Is there a way to override/clear the POST request that is sent while refreshing?
If you are using sessions you can store the last POST there and compare it to the next one you get.
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']); } 

Comments

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.

Comments

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

Comments

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.

Comments

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.

Comments

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...

Comments

0

try

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

it worked for me

Comments

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.

Comments

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.

Comments

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.

Comments

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; } ?> 

Comments

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.

Comments

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.

Comments

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>' } 

Comments

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

1 Comment

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.
-1

This works for me:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.