Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to avoid the submit due to a refresh of the page

Tags:

html

forms

php

I think that this problem occurs often on a web application development. But I'll try to explain in details my problem.

I'd like to know how to correct this behavior, for example, when I have a block of code like this :

<?
    if (isset($_POST['name'])) {
        ... operation on database, like to insert $_POST['name'] in a table ...
        echo "Operation Done";
        die();
    }

?>

<form action='page.php' method='post' name="myForm">
    <input type="text" maxlength="50" name="name" class="input400" />
    <input type="submit" name="Submit" />
</form>

When the form gets submitted, the data get inserted into the database, and the message Operation Done is produced. Then, if I refreshed the page, the data would get inserted into the database again.

How this problem can be avoided? Any suggestion will be appreciated :)

like image 414
markzzz Avatar asked Sep 10 '25 05:09

markzzz


2 Answers

Don't show the response after your create action; redirect to another page after the action completes instead. If someone refreshes, they're refreshing the GET requested page you redirected to.

// submit
// set success flash message (you are using a framework, right?)
header('Location: /path/to/record');
exit;
like image 194
coreyward Avatar answered Sep 12 '25 19:09

coreyward


Set a random number in a session when the form is displayed, and also put that number in a hidden field. If the posted number and the session number match, delete the session, run the query; if they don't, redisplay the form, and generate a new session number. This is the basic idea of XSRF tokens, you can read more about them, and their uses for security here: http://en.wikipedia.org/wiki/Cross-site_request_forgery

Here is an example:

<?php
session_start();

if (isset($_POST['formid']) && isset($_SESSION['formid']) && $_POST["formid"] == $_SESSION["formid"])
{
    $_SESSION["formid"] = '';
    echo 'Process form';
}
else
{
    $_SESSION["formid"] = md5(rand(0,10000000));
?>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
    <input type="hidden" name="formid" value="<?php echo htmlspecialchars($_SESSION["formid"]); ?>" />
    <input type="submit" name="submit" />
</form>
<?php } ?>
like image 25
Ben Avatar answered Sep 12 '25 18:09

Ben