24

I have searched many posts here and elsewhere but can't seem to find a solution to my problem. I have a page which displays database entries: database.php. These entries can be filtered with a form. When I filter them and only display the ones I am interested in I can click an entry (as a link) which takes me to that entries page (via php GET). When I am on that entries page (i.e., "view.php?id=1") and hit the back button (back to database.php), the filter form requires to confirm the form resubmission. Is there any way to prevent this?

here are some (simplified) code examples:

Database.php:

<form>
    <select>
        <option>1</option>
        <option>2
        <option>
    </select>
    <input type="submit" name="apply_filter" />
</form>
<?php
if ( isset( $_POST[ "apply_filter" ] ) ) { // display filtered entries
    $filter = $_POST[ "filter" ];
    $q = "Select * from table where col = '" . $filter . "'";
    $r = mysql_query( $q );
} else { // display all entries
    $q = "Select * from table";
    $r = mysql_query( $q );
}
while ( $rec = mysql_fetch_assoc( $r ) ) {
    echo "<a href='view.php?id=" . $rec[ "id" ] . "'>" . $rec[ "name" ] . "</a><br />"; // this is where the link to the view.php page is...
}
?>

Now as mentioned, if I click on the link, it takes me to "view.php?id=whatever". On that page, I just get the ID from the url to display that single entry:

view.php:

<?php
$id = $_GET[ "id" ];
$q = "Select * from table where id = '" . $id . "'";
$r = mysql_query( $q );
while (  ) {
    // display entry
}

?>

If I now hit the back button, the form on database.php (the one used to filter the DB results) requires confirmation for resubmission. Not only is this very annoying, its also useless to me.

How can I fix this? I hope the code examples and explanation of my problem are sufficient. If not let me know and I'll try to specify.

4

10 Answers 10

34

I know this question is old, but having this issue myself, two lines I've discovered that works are:

header("Cache-Control: no cache");
session_cache_limiter("private_no_expire");
3
  • 1
    where we have to add these lines?
    – user5876173
    Sep 25, 2017 at 7:58
  • @user3663 I used it on all pages but may work on just the interface pages, e.g. view.php in regards to OP's question. Sep 25, 2017 at 12:52
  • I got an error using session_cach_limiter. I am also using session_start . It seemed to work when i didnt use session_cache_limiter("private_no_expire"); and used session_start and header("Cache-Control: no cache"); Used it on the page that holds the submit button .
    – Glen
    Apr 21, 2020 at 10:04
9

There are two ways I know of to do this. The simple way and the hard way.

Regardless of the way, when you are dealing with a state-based page (using $_SESSION), which you should be doing to keep your pages "live" and under your control, is prevent the caching of all pages like this:

<?php
//Set no caching
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Cache-Control: no-store, no-cache, must-revalidate"); 
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

The hard way involves generating an id and storing it somewhere on the page as a hidden input or a &_SESSION cookie. Then you store the same id on the server as a $_SESSION. If they don't match, a series of preprogrammed if else type statements cause nothing to happen with the page is resubmitted (which is what it tries to do when you click back).

The easy way is to simply redirect the user back to the form submission page if the form was submitted successfully, like so:

header('Location: http://www.mydomain.com/redirect.php');

I hope this helps!

2
  • 1
    I am not understanding the "easy way".. if the user is on the "view" page there is no way to redirect him since I don't know how long he wants to look at the info on that page. I included a redirect button which takes the user back to the form page; this is no trouble. Only if the user presses back to return to the whole DB the problem presents itself. Mar 5, 2013 at 15:10
  • You'd submit from your form to Database.php then gather up all the info and redirect the user at the end of that script using a $_GET style URL in your header('Location: http://www.mydomain.com/view.php?databse=this&somethingelse=that');
    – user1781710
    Mar 5, 2013 at 15:15
3

One thing that might help is making your filter form use a GET method instead of POST.

Browsers usually prevent POST input from being automatically resubmitted, which is something they don't do when GET input is used. Also, this will let users link to your page using a filter.

1
  • 1
    This solution is best for search/filter forms. For create/update form redirect is best. Sep 2, 2015 at 10:14
2
header("Cache-Control: no cache");

session_cache_limiter("private_no_expire");

NOTE: After using the post data what you have submitted from the form then, these two lines should be used at the end of function.so, when we are back to the redirected page, it will not ask you to resubmit the page. This will work.

1

I used the answer at How do I detect if a user has got to a page using the back button? to detect whether or not the visit was triggered by a browser's back button click, and then if that was the case, I used JavaScript to reload the page. When the page is reloaded, my code already handles the corresponding validations to make sure that the form is never submitted twice. The important part in my case was forcing the page reload when the form was revisited after clicking the browser's back button. This is my code in the URL where I wanted to apply this validation:

<script type="text/javascript">
    if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
        location.reload();
    }
</script>
0

An alternative solution that also works if/when the page is reloaded involves checking the post's originality using $_SESSION. In a nutshell, check for a unique or random string.

In the form, add an input element with a value set using rand() or microtime():

<input type="hidden" name="formToken" value="<?php echo microtime();?>"/>

And then wrap the PHP function to validate and parse the form data in an if block:

if(!isset($_SESSION['formToken']) || $_POST['formToken'] !== $_SESSION['formToken'])){
       $_SESSION['formToken'] = $_POST['formToken'];
      /*continue form processing */
}
0

The solution the works for me is

$(document).ready( function() {
//prevent form submit on refresh or resubmit with back button
if ( window.history.replaceState ) window.history.replaceState( null, null, window.location.href );
}
0

Its already mentioned above but again i will say it, if you have used session_start() in your code then you just need to add this line in your header file like:-

<?php
header("Cache-Control: no cache");
?>

but if you didnt have used yet the session_start() then you can add the line below in your header file like:-

<?php
header("Cache-Control: no cache");
session_cache_limiter("private_no_expire");
?>
1
  • Why duplicate answer if you see that "it's already mentionned above" ? Also, you duplicate your answer from this of your post
    – Elikill58
    Jan 27, 2022 at 10:26
0

The following worked for me when I add this code to the end of my script after the submission/redirection

unset($_POST);
exit();

So simple but it took way too long for me to figure it out.

-2

You need to remove the request which POST data from browser history

history.replaceState("", "", "/the/result/page")

See this answer

Also you may follow the Post/Redirect/Get pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.