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.

No votes yet

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

<?php
session_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

<?php
session_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();

Your rating: None

Post new comment

 
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><code>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters (without spaces) shown in the image.