Avoid Form Resubmit on Refresh/reload

All of us write a PHP script where script submit the form and data need to put on database or in some file. This is a very important step we learn when we start doing programming in PHP. After everything went correct you may has faced the problem of resubmitting the form on refresh or back button of browser. It is a though situation. All beginners may have faced this.

There can be quite a few method for achieving this. I will discuss one to prevent resubmit of form. I do not remember what method I have followed mostly for doing this but this method should work quite correctly.
Now, you will learn how to submit Form and check errors etc and what you will do in case of error you got or got everything right.
Page:: avoid_form_resubmit.php

Form Submit and decide what to do in case of error or success !

<?php
if (count($_POST))
{
	$err = '';
	// validation check
	// if something went wrong
	if ($not_everything_good)
	{
		$err = 'Error in so so';
	}
	if ( $err == '') // no error
	{
		// Database/table insert or update
		// if everything went correctly
		$msg = 'Insert/update successful.';
		header ("Location: same_page_or_new_page.php?submit_msg=$msg");
		exit;
	}
}
?>

HTML part of preventing form resubmit page:

<html>
<head></head>
<body>
<?php echo $err; ?>
<form method=post action="">
<input type=text name=txt1 value=""/>
<input type=submit name=submit1 value="Submit it"/>
</form>
</body>
</html>

In the above script when you detect any error in user submitted data or some other kind of problems,
you want to report to user and assign that to $err variable.
If everything goes according to plan then you want to say cheer to the user and for
this you will display a message. For this you will assign value to $msg variable.

Now, discussion about avoiding form resubmit on page refresh or on back button press-
For this I have mentioned the page name at this line:
header ("Location: same_page_or_new_page.php?msg=$msg");
Now, you can decide where you want to lead the user after form submit. Wherever you want to send user, you will write this code:
Page:: same_page_or_new_page.php

Avoid Form Resubmission

<?php
if (isset($_GET['submit_msg']))
{
	echo "<p align=center>";
	echo $_GET['submit_msg'];
	echo "</p>";
}
?>

Now, you refresh page and data will not be re-submitted.

Comments are open for an year period. Please, write here on Facebook page.