I wrote something to address this. Basically, I set form data to a session variable. If the HTTP referrer is different from the name of the PHP script, the session variable resets it to a new array. Otherwise, it merges in new data into the existing form data. The script also lets you set default values, and it sanitizes input.
You could probably alter this to wipe or unset the session value, but this worked for me.
$form = array();
if(isset($_SESSION['form']) && isset($_SERVER['HTTP_REFERER']) && strrpos($_SERVER['HTTP_REFERER'], $_SERVER['SCRIPT_NAME']) !== false) {
$form = $_SESSION['form'];
}
if(isset($_SESSION['defaults']) && is_array($_SESSION['defaults'])) {
$defaults = $_SESSION['defaults'];
unset($_SESSION['defaults']);
}
else {
$defaults = array();
}
function addValues($arr, &$form) {
foreach($arr as $key=>$value) {
$form[$key] = mysql_real_escape_string(strip_tags(stripslashes($value)));
}
}
if(sizeof($_POST) > 0) {
addValues($_POST, $form);
}
if(sizeof($_GET) > 0) {
addValues($_GET, $form);
}
$_SESSION['form'] = array_merge($defaults, $form);
Usage:
$_SESSION['defaults'] = array(
'button'=>'first'
);
include_once "formdata.php";
...
<form>
<p>Form data for button (always a valid index): <?php echo $_SESSION['form']['button'] ?></p>
<button value="test" name="button" type="submit">Test</button>
</form>
Note that this allows great shorthand for forms where you don't have to test for indices and use if statements to switch between default and form values to set form values on initial load and post-back.