To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier.
I am getting this firefox error. Though I am unsetting all variables at end of page using <?php unset[$_POST] ?>.. But if I update some record or update page again using this. Than I got above error.
After processing the request you should made a redirection to the same page to avoid such type of warning.
Saying OK to the warning message above will resubmit your form again and the PHP processing will be repeated. This should be avoided otherwise your database will have duplicated records if there is an INSERT query is getting processed.
header('location:http://www.example.com/currentpage');
die();
EDIT
You should do it something like below:-
if(isset($_POST['submit']))
{
//filter the data and validate user input
//do some stuff
/* Redirect users back to same url instead of refreshing page with javascript*/
header('location:http://www.example.com/currentpage');
die();
}
Related
Suppose there is a web form in your PHP page and it posts values by POST method to same page.
Then you get values from $_POST and insert them to Mysql table. It is OK.
But when I want to feedback (success or error), I get confused.
I use bootstrap toast messages. For example, when input values are not regular or insert query fails, toast message says: Error: New record fails!
When insert query succeeds, toast message should say: Success!: New Record Added!
But visitor also can refresh the page, it means double time same code and double insert
To prevent resubmitting the page, I use header code. After successfull insert query, I redirect the page forexample like this:
header("location: page.php?NewRecord=Ok");
So I check by PHP code; is there any GET value in URL, and if there is "NewRecord=Ok", toast message says: Success!: New Record Added!
But, when visitor referesh the page, the URL does not change. It is still "page.php?NewRecord=Ok".
Thus, the visitor can still see same toast message by refreshing same page.
I think you understand me. What do you advice me?
In my solution use session ($_SESSION).
It will save your notify to session and after refreshing it will delete self.
Use it like:
//At saving to database:
$_SESSION["notice"] = "saved";
//after refresh (meaning somewhere on page where is not button click needed):
if (isset(t$_SESSION["notice"])) {
unset($_SESSION["notice"];
showmessage(); // replace with your message function
}
Because unset function it will not appear many times but just once
So here is the deal,
I am using HTML forms to transfer variables from page to page and PHP script to create pages based on values submitted.
In general it looks like this: from the catalog of items you select what you want and the next page shows details for this specific item. Everything works perfect, except one thing:
Whenever I use browser's back button, I always get the error: ERR_CACHE_MISS and I need to refresh page and then confirm that I really want to resubmit data.
Is there any way to fix this, so my customers would be able just to use back button as they supposed to.
Here is the full text that browser provides me:
This webpage requires data that you entered earlier in order to be
properly displayed. You can send this data again, but by doing so
you will repeat any action this page previously performed. Reload this
webpage. Press the reload button to resubmit the data needed to load
the page. Error code: ERR_CACHE_MISS
When you post forms with php, or any other data, you may come back to the page and find a message in the browser like "Document Expired" or "Confirm Form Resubmission With Chrome". These messages are a safety precaution the browser uses with sensitive data such as post variables. The browser will not automatically give you the fresh page again. You must reload the page by clicking try again or with a page refresh. Then, it operates as you would expect it to.
However, the php coder can work around the annoying message from the browser by adding a little code into the script. The example shows a couple of lines of code that can be added above session_start() in order to be able to go back and forth to the page when you post without any hangups.The 'private_no_expire' mode means that the client will not receive the expired header in the first place.
header('Cache-Control: no cache'); //no cache
session_cache_limiter('private_no_expire'); // works
//session_cache_limiter('public'); // works too
session_start();
**Some background: Credit goes to bruce (sqlwork.com) for his excellent explanation.
This web page requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed. Press Reload to resend that data and display this page.
Because of the sloppy coding practices of web developers browsers were forced to add this message. the scenario is as follows:
1) user fills in form and submits (posts form)
2) the server process the post data and responds with a new page (confirm) marked as not cacheable
3) the user navigates to a new page.
4) the user press back:
for the the browser to display the page in step 2, because its marked no-cache, it must request it from the server, in other words do the repost of the data (do step 1). here is were the sloppy coding came in, if this was an credit card charge, and repost detection was not on the server, the card is charged twice. this was (is) so common a problem, that the browsers had to detect this and warn the users.
the best fix is in step two, the server sends a redirect to the confirm page. then when the user accesses the confirm via history or back, its a get request, not a post request and will not show the warning.
note: webform's postback model lends itself to this problem. also avoid server transfers.
My solution
$_SESSION['home'] used to store any errors on home page.
$_SESSION['tempEmail'] used to echo value on php form.
Note: Use one unique session variable for each page that has a HTML form for error handling and also any session variable for each value that is echoed on HTML form.
<?php
session_start();
//Initialize variables not initialized without overwriting previously set variables.
if(!isset($_SESSION['home'])) {
$_SESSION['home']="";
$_SESSION['tempEmail']="";
}
Optional - If logged in, assign email address to the $_SESSION['tempEmail'] variable (if not previously done) to pre-fill HTML form.
if(isset($_POST['Submit'])){
---your code---
//Error message(s) examples
$_SESSION['home'] = "Email and Password do not match, please try again.";
header("Location: " . $_SERVER['REQUEST_URI']);
$_SESSION['home'] = "Email address format is invalid. Please recheck.";
header("Location: " . $_SERVER['REQUEST_URI']);
//success
unset ($_SESSION['home']); //optional, unset to clear form values.
header ("location: nextpage.php");
---or---
header("Location: " . $_SERVER['REQUEST_URI']); //re-post to same page with the $_SESSION['home'] success message.
}
?>
<body>
Error box
<span><strong class="error"><?php echo $_SESSION['home'] ?></strong></span>
HTML form
<form action="#" name="loginform" method="post" >
<input type="text" name="userEmail" maxlength="50" title="Enter Your email" autocomplete="off" value="<?php echo htmlspecialchars($_SESSION['tempEmail']); ?>" placeholder="enter email" required/>
<input type="submit" name="Submit" value="Submit">
</form>
</body>
Not recommended to use on payment page,see discussion above. Tested in Firefox, Chrome, Safari, and IE9. The annoying messages are gone when using back button. Ensure that output buffering is turned "on" in your php script or php.ini to avoid header warnings. You can check your php.ini file for the following;
output_buffering=On
I found that using just :
header('Cache-Control: no cache'); //disable validation of form by the browser
resolve the problem
None of the other answers worked for me.
I don't want to redirect
Setting different headers didn't work
I already use tokens in my post to ensure re-submission can't happen
I post to the same url the form is showing on
This simple javascript fixes my issue of the back button throwing "ERR_CACHE_MISS"
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
I tried this answer and it's ok.
You have to put this code before: session_start():
session_cache_limiter('private, must-revalidate');
session_cache_expire(60);
Good luck
<?php
if(isset($_POST['submit']))
{
//submission goes here
}
?>
Is this what you were thinking?
edit - SQL really is a beautiful thing to work with, I see it's been added as a recommendation in a comment, and I concur to use SQL if you can, its fast, intuitive and efficient.
I have a form that acts as a filter to a list of inventory.
The form works well but I have been using get in order for the user to flip through pages, for example:
Next page
<?php } ?>
I am getting my data from XML and this is the way I've found works best. However, the form to filter is POST and if a user clicks next page and tries to use the filter afterwards(bunch of drop boxes) then It also uses the get-parameters that have been passed to the URL from the link.
Is there a way, that no form submit, It will reset all the parameters?
http://www.website.com/used-cars/?pos=10&q=Model-Corolla%2C&srt=KMDfr
That would be preform submission, and once the form is submitted, it will look like this:
http://www.website.com/used-cars/
And there will be no GET variables for the page to get anymore.
Yes, after you're done with your processing, call
header("Location: /used-cars/");
die();
And it will redirect the user to the wanted page.
First of all, don't just use the default header("Location...") alone, because that would send a 302 Found (previously called: Moved Temporarily) response, which kinda "lies" about the actual behavior (as it still means "The requested resource resides temporarily under a different URI"). Worse yet: if a form uses POST (which most do), a conforming browser should even ask for permission before redirecting, according to HTTP 1.1.
So, to properly reset form URIs with a GET, use 303 See Other instead, which was specifically added for this purpose.
(It's nice to also combine it with a 201 Created response intended to ack. successful form submissions, so adding a
header("HTTP/2.0 201 Created") to the result page is a nice touch.)
But, to address your old comment "Where would I add this php code? I'm not sure where to put it, the form submission reloads the current page." (though you probably figured it out since then ;) ):
You'll have to handle not only two, but at least three, or even four cases (in conditional branches):
You send the form for displaying + submitting.
You receive the the form data, store it somewhere (i.e. "create a new resource", the idea behind 201 Created), and redirect to a clean URI.
To avoid redisplaying the form again as if nothing had happened (or redirecting forever to the same page), you must detect if you have just redirected to yourself...
But, since you've now removed all the inputs from the URI, you must use some other means to keep track of state. Some straightforward ways for that:
a) Redirect to a different URI.
b) Use a PHP session.
And, finally, if needed: reset and display the form again for new inputs.
Here's an example (with 3/b, and a kind of "faked" 4, for simplicity):
session_start();
if (isset($_GET['some_input'])) // Case 2: We got data!
{
file_put_contents("result", $_GET['some_input']);
$_SESSION['redir'] = true;
header("Location: /used-cars/", true, 303);
exit;
}
else if (isset($_SESSION['redir'])) // Case 3: We have redirected!
{
unset($_SESSION['redir']);
http_response_code(201); // Acknowledge receiving the form data.
echo "OK, we have happily processed the last submitted data: ",
file_get_contents("result"), "<br>";
echo "Reload the page to fill the form again!"; // Case 4: Reset...
}
else // Case 1: Send the form...
{
echo <<<_
<form>
<input type="text" name="some_input">
<input type="submit">
</form>
_;
}
i am trying to sort out the error section of my settings page, and because i am validating all the data on a seperate script i have to use the url variables to check whether an error is present
so it looks like this if there is an error
localhost/site123675/settings.php?eid=1
however, the error shows fine, but i want a way to remove it, becuase if the user gets an error then enters a correct answer, it still shows the same error.
So, how can i clear the url of any variables before the user resubmits the page?
Any ideas?
Not exactly sure what exact problem you're facing, but you could just do a header redirect:
if (isset($_GET['eid'])) {
header('Location: /site123456/settings.php');
exit;
}
When a user creates their own account, if there is an error I want to redirect them to the same page but display the errors at the top.
What's the best way to do this?
Structure your page as follows (in rough pseudo-code)
if (doing a post) {
process input
if (post is ok) {
redirect to success page
} else {
build error messages
}
}
if (error messages available) {
display errors
}
display form(filled in with previously submitted values)
i like to create a function named set_feedback() that sets the error in a session variable. then i have this other function get_feedback() that retrieves the information and unset the variable.
I save the error into the session and remove it once it was rendered. As you will probably abort the pages execution on a redirect it will never reach the code responsible for rendering thus leaving it in the session.