How do I stop double posts in php
I'm helping someone with an old someone else made admin program to add / edit / delete records
Some of the people working on it are always pressing the back and forward button and reposting the info multiple times. Is there a way keep this from happening?
not the real code but close enough
<form method="post" action="addrecord.php">
<input type="text" name="title" />
..
..
..
<input type="submit" value="Add Record" />
</form>The addrecord.php page
<?
include_once('dataconnection.php');
$title=$_POST['title'];
more fields
.
.
.
$sql = "INSERT INTO records (title,description,text) VALUES ('$title','$description','$text')";
mysql_query($sql);
?>
<h2>Record Added<h2>
return to <a href="addrecordform.php">Add Record</a><br />
return to admin <a href="admin.php">Admin</a>Often they will press back button then forward or click refresh and complain about multiple copies of the same entry.

Replies
redirect or sessions
I've used two different ways either redirecting after the post or using sessions to only allow one post
With Sessions
on the submit php page
<?phpsession_start();// should start session before any text is output to page
$hash = md5(time());//generate hash based on current time
$_SESSION['formhash'] = $hash;//store the hash in session
?>
<form method="post" action="addrecord.php">
<input type="hidden" name="formhash" value="<? print $hash;?>" />
your normal input
fields
.
.
<input type="submit" value="add record" />
</form>
Now on your addrecord.php page
<?phpsession_start();// should start session before any text is output to page
$hash = $_SESSION['formhash'];
$formhash = $_POST['formhash'];
if ($hash == $formhash){
$_SESSION['formhash'] = NULL;//or just any other value
//do your normal get form values insert into db
}else{
//dont do a db insert the hash value is not correct
}
?>
The redirect way:
On addrecord.php page
<?php
//do all of your normal things for getting form values and inserting into db
//Instead of displaying links to return to other pages redirect to another page
//A refresh after a header location should only redisplay the text from that page and not do any data inserts
header('Location: http://www.example.com/admin/recordadded.php');
exit();
Post new comment