[PHP] Stopping the dreaded refresh

Soldato
Joined
18 Oct 2002
Posts
7,635
Location
Sutton Coldfield, Birmingham
I have a form which once submitted, sends the data to the same page and is handled by an if statement.

However, if that person then refreshes the page, the data is submitted again, even though the form could be blank.

How can I get around this? I can't use sessions, are there any alternatives to using cookies?
 
What he said.

If you could use sessions, then I would suggest having an intermediate script (in the same file) which processes the POST data, sets session variables accordingly and then redirects to the page in question.
 
Dj_Jestar said:
Generate an id field before the form is submitted and store it in a hidden field in the form, then validate the id before allowing submission of the form.

Thats a good idea and I have just tried that but whenever the form is submitted, a new random ID is generated and so it doesn't work :confused:
 
Code:
<?php
session_start();

if (!isset($_POST['id'])) {

    $ID = md5(rand(0,10000));

    echo <<<PAGE
<form method="post" action="">
  <input type="hidden" name="id" value="{$ID}" />
  <input type="submit" />
</form>
PAGE;

} else {
    
    if ((isset($_SESSION['oldid'])) && ($_SESSION['oldid'] == $_POST['id'])) {
        echo 'Not Submitted';
    } else {
        $_SESSION['oldid'] = $_POST['id'];
        echo 'Submitted';
    }
    
}

?>

For an example, but not the best method you should use as you will need to reserve the ID, or similar on a more permanent basis. (and it uses sessions, but tables can be used easily.)

Another method that most boards use is to check if the content is identical to what has been posted in the last x minutes, or if it is a pure duplicate of something already fullstop, or simply not allow users to post more than 1 post every x seconds.
 
Last edited:
Back
Top Bottom