I detect a form submit on an ‘addrecord’ button being pressed, and then I reset the value of that ‘addrecord’ button in the $_POST array:
if(array_key_exists('addrecord', $_POST))
{
var_dump($_POST);
if($_POST['addrecord'] == "ADD RECORD")
{
$_POST['addrecord'] = "Handled already."; // prevents a 'reload'
// from adding the same record again
// now do the 'addrecord' -- just once -- to the database
}
else
{
// yay -- we avoided adding the same record on a browser reload
}
}
And here is the problem — when I click the ‘reload’ button in Firefox 8, the var_dump above shows me —
the post array’s ‘addrecord’ value is NOT the string “Handled already.” — it is still “ADD RECORD”.
-
when the user clicked the ‘addrecord’ button, the server gets a POST array and the addrecord button has the value
“ADD RECORD” — here is the add record button on my form:<input type="submit" name="addrecord" value="ADD RECORD" /> -
and then on the server side, I see the value of ‘addrecord’ is “ADD RECORD” and I change the POST array’s ‘addrecord’ element
from “ADD RECORD” to “Handled already.” -
and then the server sends a new page to the browser that says “Record Added!”
So it seems like the POST array’s value of the ‘addrecord’ element is no longer “ADD RECORD”, because I changed it to “Handled already”. If the user does not press the ‘add record’ button on the form again but only does a page reload — how then can the browser re-set the POST array from “Handled already” — to “ADD RECORD”? Why, when the server receives the page reload, does the POST array’s ‘addrecord’ element lose the value I set previously, “Handled already.” ?
Because when I click ‘reload’ on the browser, var_dump tells me — that is exactly what has happened: the POST array’s ‘addrecord’ value is now right back to “ADD RECORD” — even though the user did NOT click on the form’s add record button.
Why? Does the browser somehow have a cached copy of the values used to fill the POST array on the server, so that even if you change the POST array in php on the server, that the browser will re-submit a cached copy of all the old form values?
Yes, the browser remembers the POST data, and that cached information is unaffected by anything you write in your form-processing PHP code. If the user hits reload, the same POST data will be sent again.
One alternate approach to keep the reload from inserting the same data again is to include a “submission identifier” column in your database column. When you display the form for the user to fill out, include a hidden form field with a unique identifier — see PHP’s uniqid() or microtime() functions. Then you can either:
a) query your database before sending the INSERT command, to see if a form with that submission ID has already been submitted, or
b) simply add a UNIQUE index to that new column in your database table, so that duplicate records can’t be created.