How to prevent form resubmission when page is refreshed (F5 / CTRL+R)
Asked Answered
W

21

245

I have a simple form that submits text to my SQL table. The problem is that after the user submits the text, they can refresh the page and the data gets submitted again without filling the form again. I could redirect the user to another page after the text is submitted, but I want users to stay on the same page.

I remember reading something about giving each user a unique session id and comparing it with another value which solved the problem I am having but I forgot where it is.

Wardmote answered 12/6, 2011 at 4:24 Comment(7)
Post/Redirect/Get.Archlute
Why do you not want to redirect user to another page?Barcus
@Adam: Because this is excess to do another request to the server which in turn will fetch some data from DB again. But this is resource wasting because we already fetch all required data while processing POST requestCressler
@EugenKonkov in the PRG pattern, you would just redirect to a page that shows a success message. No further fetching from DB needed.Barcus
@Adam: You also may display the whole record which is created by POSTing data. In this case you need to SELECT it from DB. For example when you create the invoice you are redirected to /invoices/53 which display the whole invoice instead of just 'success'Cressler
@Archlute OP wants to stay on the same page. Redirect is not an option as it is literally the act of leaving the page.Lamella
I used your comments and made the redirect with the same URL as the form uses. since this is a POST request there's nothing in the query string, therefor i use Location: https://domain/same_script_path ... - and i stay in the same page just w/o the form dataYan
C
135

Use the Post/Redirect/Get pattern. http://en.wikipedia.org/wiki/Post/Redirect/Get

With my website, I will store a message in a cookie or session, redirect after the post, read the cookie/session, and then clear the value of that session or cookie variable.

Ceilidh answered 12/6, 2011 at 4:26 Comment(8)
This makes chrome unusable for development where business is requiring only a post!Privation
If you use the PRG pattern, then you actually leave the page right? Wasn't the question how to make things work when not redirecting?Barcus
It seems to me that if you redirect to the same page, then $_POST is cleared. As I understand it, that was the desired effect. That was MY desired effect, anyway. I think the answer would be better if it made that explicit, though.Bear
Works well, my only recommendation is to make sure you enable strict error testing so you're catching errors locally while developing, otherwise they can go unnoticed.Ylem
Doesn't answer the question. Not sure why it's the accepted answer.Lamella
Another solution is to add a location header in your backend POST handler, which will automatically redirect to your POST callee page. For example if you're on PHP you could do header('location: yourpage.php')Wandie
Using PRG, you lose context, it's a bad solution for me. We should not do that.Cookbook
Could you please compare these approaches? 1 AJAX request 2 Post-Redirect-Get(PRG) pattern 3 JS window.history.replaceState IMHO: 1 AJAX is probably the best solution (but requires some time to prepare the form validation to work with the DOM elements) 2 PRG is not always suitable(if you have validation, then you will need to use the intermediary thing to pass the errors with a session that is not that good) 3 JS solution seems like a crutch,isn't it? I would do appreciate any comments/critic about it. Let me know the pros/cons of each. Are there any downfalls using AJAX?Yusem
P
298

I would also like to point out that you can use a javascript approach, window.history.replaceState to prevent a resubmit on refresh and back button.

<script>
    if ( window.history.replaceState ) {
        window.history.replaceState( null, null, window.location.href );
    }
</script>

Proof of concept here: https://dtbaker.net/files/prevent-post-resubmit.php (Link no longer works)

I would still recommend a Post/Redirect/Get approach, but this is a novel JS solution.

Powerless answered 13/8, 2017 at 2:46 Comment(8)
Tks, this is work perfect for me, it just had to create 404 page avoid user missunderstandingTearful
it doesn't work in safari, it changed href but still keep the data with post request to submitMariettemarigold
This worked for me thank you! Why do you recommend the PRG approach?Pontiac
Thanks, it's Amazing, i test its working very well with google chromePrevot
Worked perfectly on a system where we couldn't get the post/redirect/get approach to work. Very nice, thanks.Fiester
I presumed that, anybody using a browser without javascript would still encounter the same issue. Perhaps https://mcmap.net/q/116232/-how-to-prevent-form-resubmission-when-page-is-refreshed-f5-ctrl-r is more suiting.Mammet
I consider manipulating the security and safety side of a website using client side code only - a big no-no. Server should resist against misuse. Client side code should be only a helpful addendum.Primaveras
I completely concur with the last 2 comments here. Personally, I would go with the solution @Keverw mentioned. A small "bonus" there, is that it will also work in slightly older browsers that might not even support history.replaceStateRoundhead
C
135

Use the Post/Redirect/Get pattern. http://en.wikipedia.org/wiki/Post/Redirect/Get

With my website, I will store a message in a cookie or session, redirect after the post, read the cookie/session, and then clear the value of that session or cookie variable.

Ceilidh answered 12/6, 2011 at 4:26 Comment(8)
This makes chrome unusable for development where business is requiring only a post!Privation
If you use the PRG pattern, then you actually leave the page right? Wasn't the question how to make things work when not redirecting?Barcus
It seems to me that if you redirect to the same page, then $_POST is cleared. As I understand it, that was the desired effect. That was MY desired effect, anyway. I think the answer would be better if it made that explicit, though.Bear
Works well, my only recommendation is to make sure you enable strict error testing so you're catching errors locally while developing, otherwise they can go unnoticed.Ylem
Doesn't answer the question. Not sure why it's the accepted answer.Lamella
Another solution is to add a location header in your backend POST handler, which will automatically redirect to your POST callee page. For example if you're on PHP you could do header('location: yourpage.php')Wandie
Using PRG, you lose context, it's a bad solution for me. We should not do that.Cookbook
Could you please compare these approaches? 1 AJAX request 2 Post-Redirect-Get(PRG) pattern 3 JS window.history.replaceState IMHO: 1 AJAX is probably the best solution (but requires some time to prepare the form validation to work with the DOM elements) 2 PRG is not always suitable(if you have validation, then you will need to use the intermediary thing to pass the errors with a session that is not that good) 3 JS solution seems like a crutch,isn't it? I would do appreciate any comments/critic about it. Let me know the pros/cons of each. Are there any downfalls using AJAX?Yusem
E
35

You can prevent form resubmission via a session variable.

First you have to set rand() in a textbox and $_SESSION['rand'] on the form page:

<form action="" method="post">
  <?php
   $rand=rand();
   $_SESSION['rand']=$rand;
  ?>
 <input type="hidden" value="<?php echo $rand; ?>" name="randcheck" />
   Your Form's Other Field 
 <input type="submit" name="submitbtn" value="submit" />
</form>

After that check $_SESSION['rand'] with textbox $_POST['randcheck'] value like this:

if(isset($_POST['submitbtn']) && $_POST['randcheck']==$_SESSION['rand'])
{
    // Your code here
}

Make sure you start the session on every file you are using it with session_start()

Equilateral answered 4/8, 2016 at 13:3 Comment(9)
we can use <input type="hidden" name="randcheck" id="randcheck" value="<?php echo microtime(); ?>" /> insteadParting
Yes we can use microtime() as well as time() also instead of rand() , whatever function or variable that gives different value we can use it. BUT make sure that you set that value to SESSION variable. here SESSION is must to check with randcheck field and to prevent from resubmit form.Equilateral
shouldn't the session variable be cleared after checking if the session and post vars match?Terza
@Terza I believe the idea by @Equilateral is that after $_POST of the form data the same page reloads re-setting the session and post variables. Also creation of variables should takes place after checking if the variables match. Therefore unset is not needed.Northumberland
I am currently using this kind of method, with tokens. However, this will create a problem on multi-tab submission. Since it will create new rand() on each tab, and overwrite the session value, this means older tabs opened is no longer valid. Any suggestion?Tague
@Tague you'd need to store that token in it's own field, like $_SESSION['specificform']['rand']Classic
@DougCassidy The scenario that I was talking about is opening the same specific form on two different tabs, the form opened on the first tab will not be submitted since the new tab generate new token.Tague
@Tague yes, but I'm not sure why you'd have the same form, open on 2 tabs. Maybe you'd have /theform.php?thistab=1 /theform.php?thistab=2 and keep track of which rand() goes with which tab. $_SESSION['specificform']['tab1']['rand']Classic
after the comparison a $_SESSION["rand"] = NULL was nessesary here to make it work.Mowry
M
30

I use this javascript line to block the pop up asking for form resubmission on refresh once the form is submitted.

if ( window.history.replaceState ) {
  window.history.replaceState( null, null, window.location.href );
}

Just place this line at the footer of your file and see the magic

Monazite answered 23/9, 2018 at 8:33 Comment(5)
Would be nice a version of this that can't be disabled from the client side, but it is short, easy, fast... and do what it needs to do. Keeps the history so the user can navigate back, without resending post.Ergotism
That solved the issue for me. Does this method have any downsides though?Minhminho
I put this code after the <form>, and when the user goes back a page, it doesn't return to the previous page but to the page before that one in the chain of POSTs.Exoergic
This will not work in Safari, use en.wikipedia.org/wiki/Post/Redirect/GetGrantham
Downside is that it can be easily bypassed by just disabling javascript in the browser.Mowry
C
17

You should really use a Post Redirect Get pattern for handling this but if you've somehow ended up in a position where PRG isn't viable (e.g. the form itself is in an include, preventing redirects) you can hash some of the request parameters to make a string based on the content and then check that you haven't sent it already.

//create digest of the form submission:

    $messageIdent = md5($_POST['name'] . $_POST['email'] . $_POST['phone'] . $_POST['comment']);

//and check it against the stored value:

    $sessionMessageIdent = isset($_SESSION['messageIdent'])?$_SESSION['messageIdent']:'';

    if($messageIdent!=$sessionMessageIdent){//if its different:          
        //save the session var:
            $_SESSION['messageIdent'] = $messageIdent;
        //and...
            do_your_thang();
    } else {
        //you've sent this already!
    }
Childhood answered 2/5, 2013 at 9:26 Comment(7)
Thanks for sharing but this doesn't seem to work. Refreshing the page does indeed resubmit the form for me. Perhaps I'm missing something?Wyrick
Refreshing the page will resubmit everything but we choose only to process the submission data if its different from the data sent last time (which we store in the session var 'messageIdent'). Are you processing your form submission within the 'if messageIdents are different' clause (ie where 'do_your_thang()' is)?Childhood
Thanks for your reply. I ended up just implementing the Post / Redirect / Get pattern, so, I don't remember now what exactly was tripping me up. Thanks again for circling back, though.Wyrick
This method is not meant to block resubmission ... but to Detect resubmission so you can alter your code to not "do" whatever you would do if this were a fresh submission. In other words: With this method you can detect the "original" submission and place your data. If it's NOT original, don't place your data. Either show a "dupe attempt" warning or perhaps show a "confirmation" instead.Gynaecocracy
For this to work you must have started a session by adding session_start(); at the beginning of the file. w3schools.com/php/php_sessions.asp says Note: The session_start() function must be the very first thing in your document. Before any HTML tags.Poteet
Unfortunately, with PRG, when the user opens more tabs from the same session then they can send Content#1 from the first tab and the Content #2 from the second tab. Now the session stores only the most recently sent content so Content #1 can be sent again from the first tab and Content #2 again from the second one, and so on. So, you should store the hash of not just the most recent conent but that of all of them while the session lasts. Or, you can delete the stored hashes after a tolerance period or if there are too many of them.Citify
It makes no sense to say "You should use PRG" to answer this question when it is literally impossible to use PRG and also stay on the same page.Lamella
H
16

When the form is processed, you redirect to another page:

... process complete....
header('Location: thankyou.php');

you can also redirect to the same page.

if you are doing something like comments and you want the user to stay on the same page, you can use Ajax to handle the form submission

Haggi answered 12/6, 2011 at 4:26 Comment(0)
C
15

I found next workaround. You may escape the redirection after processing POST request by manipulating history object.

So you have the HTML form:

<form method=POST action='/process.php'>
 <input type=submit value=OK>
</form>

When you process this form on your server you instead of redirecting user to /the/result/page by setting up the Location header like this:

$cat process.php
<?php 
     process POST data here
     ... 
     header('Location: /the/result/page');
     exit();
?>

enter image description here

After processing POSTed data you render small <script> and the result /the/result/page

<?php 
     process POST data here
     render the <script>         // see below
     render `/the/result/page`   // OK
?>

The <script> you should render:

<script>
    window.onload = function() {
        history.replaceState("", "", "/the/result/page");
    }
</script>

The result is:

enter image description here

as you can see the form data is POSTed to process.php script.
This script process POSTed data and rendering /the/result/page at once with:

  1. no redirection
  2. no rePOST data when you refresh page (F5)
  3. no rePOST when you navigate to previous/next page through the browser history

UPD

As another solution I ask feature request the Mozilla FireFox team to allow users to setup NextPage header which will work like Location header and make post/redirect/get pattern obsolete.

In short. When server process form POST data successfully it:

  1. Setup NextPage header instead of Location
  2. Render the result of processing POST form data as it would render for GET request in post/redirect/get pattern

The browser in turn when see the NextPage header:

  1. Adjust window.location with NextPage value
  2. When user refresh the page the browser will negotiate GET request to NextPage instead of rePOST form data

I think this would be excelent if implemented, would not? =)

Cressler answered 12/11, 2017 at 9:51 Comment(0)
M
9
  1. Use header and redirect the page.

    header("Location:your_page.php"); You can redirect to same page or different page.

  2. Unset $_POST after inserting it to Database.

    unset($_POST);

Matazzoni answered 8/3, 2013 at 6:21 Comment(3)
Unsetting $_POST doesn't affect form resubmission at all, at least not in Chrome.Ghastly
It will not work. When user go to back page it perform the setting up of POST variables once again.Formidable
What's the reason for using unset? Please add some explanation to your answer such that others can learn from itHardpan
A
7

A pretty surefire way is to implement a unique ID into the post and cache it in the

<input type='hidden' name='post_id' value='".createPassword(64)."'>

Then in your code do this:

if( ($_SESSION['post_id'] != $_POST['post_id']) )
{
    $_SESSION['post_id'] = $_POST['post_id'];
    //do post stuff
} else {
    //normal display
}

function createPassword($length)
{
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;

    while ($i <= ($length - 1)) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    return $pass;
}
Akbar answered 21/8, 2014 at 6:49 Comment(2)
I actually just wrote something similar to this, but didn't go through the trouble to create a password, I just enumerated my forms (eg: steps 1-5), so if they're equal we're cool to move on, else don't save to db or send emails. But let the user land wherever it takes him.Holley
I think this is a better solution than reload the page, since i show a message when post succesfull and reloading the page will delete the message. this works grate for me, you also can use a uniqidUtilitarian
G
4

A refined version of Moob's post. Create a hash of the POST, save it as a session cookie, and compare hashes every session.

// Optionally Disable browser caching on "Back"
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Expires: Sun, 1 Jan 2000 12:00:00 GMT' );
header( 'Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT' );

$post_hash = md5( json_encode( $_POST ) );

if( session_start() )
{
    $post_resubmitted = isset( $_SESSION[ 'post_hash' ] ) && $_SESSION[ 'post_hash' ] == $post_hash;
    $_SESSION[ 'post_hash' ] = $post_hash;
    session_write_close();
}
else
{
    $post_resubmitted = false;
}

if ( $post_resubmitted ) {
  // POST was resubmitted
}
else
{
  // POST was submitted normally
}
Gagne answered 4/2, 2016 at 22:10 Comment(1)
In my case, I want form submits to be re-evaluated but a refresh of the URL containing query parameters should be ignored. I achieved this with the above code, and only had to change "$_POST" into "$_GET".Tungsten
B
2

Basically, you need to redirect out of that page but it still can make a problem while your internet slow (Redirect header from serverside)

Example of basic scenario :

Click on submit button twice

Way to solve

  • Client side

  • Server side

    • Using differentiate based hashing timestamp / timestamp when request was sent.
    • Userequest tokens. When the main loads up assign a temporary request tocken which if repeated is ignored.
Betts answered 8/6, 2016 at 1:28 Comment(0)
E
2

How to prevent php form resubmission without redirect. If you are using $_SESSION (after session_start) and a $_POST form, you can do something like this:

if ( !empty($_SESSION['act']) && !empty($_POST['act']) && $_POST['act'] == $_SESSION['act'] ) {
  // do your stuff, save data into database, etc
}

In your html form put this:

<input type="hidden" id="act" name="act" value="<?php echo ( empty($_POST['act']) || $_POST['act']==2 )? 1 : 2; ?>">
<?php
if ( $_POST['act'] == $_SESSION['act'] ){
    if ( empty( $_SESSION['act'] ) || $_SESSION['act'] == 2 ){
        $_SESSION['act'] = 1;
    } else {
        $_SESSION['act'] = 2;
    }
}
?>

So, every time when the form is submitted, a new act is generated, stored in session and compared with the post act.

Ps: if you are using an Get form, you can easily change all POST with GET and it works too.

Elastance answered 22/9, 2017 at 14:26 Comment(0)
C
1

The $_POST['submit'] variable would not exist on initial loading of page, and curl can be run only if below condition is true.

if($_POST['submit'] == "submit"){

// This is where you run the Curl code and display the output
  $curl = curl_init();



//clear $post variables after posting
$_POST = array();

}
Consternate answered 30/7, 2021 at 15:36 Comment(0)
O
0

After inserting it to database, call unset() method to clear the data.

unset($_POST);

To prevent refresh data insertion, do a page redirection to same page or different page after record insert.

header('Location:'.$_SERVER['PHP_SELF']);

Ostwald answered 1/6, 2016 at 16:16 Comment(1)
Please add some explanation to your answer such that others can learn from it - why is that unset call needed? What would happen if you skipped it?Hardpan
B
0

Using the Post/Redirect/Get pattern from Keverw answer is a good idea. However, you are not able to stay on your page (and I think this was what you were asking for?) In addition, it may sometimes fail:

If a web user refreshes before the initial submission has completed because of server lag, resulting in a duplicate HTTP POST request in certain user agents.

Another option would be to store in a session if text should be written to your SQL database like this:

if($_SERVER['REQUEST_METHOD'] != 'POST')
{
  $_SESSION['writeSQL'] = true;
}
else
{
  if(isset($_SESSION['writeSQL']) && $_SESSION['writeSQL'])
  {
    $_SESSION['writeSQL'] = false;

    /* save $_POST values into SQL */
  }
}
Barcus answered 22/6, 2016 at 14:58 Comment(0)
T
0

As others have said, it is not possible to out of using post/redirect/get. But at the same time it is quite easy to do what you want to do server side.

In your POST page you simply validate the user input but do not act on it, instead you copy it into a SESSION array. You then redirect back to the main submission page again. Your main submission page starts by checking to see if the SESSION array that you are using exists, and if so copy it into a local array and unset it. From there you can act on it.

This way you only do all your main work once, achieving what you want to do.

Timbuktu answered 20/11, 2017 at 21:42 Comment(0)
S
0

I searched for solution to prevent resubmission in a huge project afterwards. The code highly works with $_GET and $_POST and I can't change the form elements behaviour without the risk of unforeseen bugs. So, here is my code:

<!-- language: lang-php -->
<?php

// Very top of your code:

// Start session:
session_start();

// If Post Form Data send and no File Upload
if ( empty( $_FILES ) && ! empty( $_POST ) ) {
    // Store Post Form Data in Session Variable
    $_SESSION["POST"] = $_POST;
    // Reload Page if there were no outputs
    if ( ! headers_sent() ) {
        // Build URL to reload with GET Parameters
        // Change https to http if your site has no ssl
        $location = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        // Reload Page
        header( "location: " . $location, true, 303 );
        // Stop any further progress
        die();
    }
}

// Rebuilt POST Form Data from Session Variable
if ( isset( $_SESSION["POST"] ) ) {
    $_POST = $_SESSION["POST"];
    // Tell PHP that POST is sent
    $_SERVER['REQUEST_METHOD'] = 'POST';
}

// Your code:
?><html>
    <head>
        <title>GET/POST Resubmit</title>
    </head>
    <body>

    <h1>Forms:</h1>
    <h2>GET Form:</h2>
    <form action="index.php" method="get">
        <input type="text" id="text_get" value="test text get" name="text_get"/>
        <input type="submit" value="submit">
    </form>
    <h2>POST Form:</h2>
    <form action="index.php" method="post">
        <input type="text" id="text_post" value="test text post" name="text_post"/>
        <input type="submit" value="submit">
    </form>
    <h2>POST Form with GET action:</h2>
    <form action="index.php?text_get2=getwithpost" method="post">
        <input type="text" id="text_post2" value="test text get post" name="text_post2"/>
        <input type="submit" value="submit">
    </form>
    <h2>File Upload Form:</h2>
    <form action="index.php" method="post" enctype="multipart/form-data">
        <input type="file" id="file" name="file">
        <input type="submit" value="submit">
    </form>

    <h1>Results:</h1>
    <h2>GET Form Result:</h2>
    <p>text_get: <?php echo $_GET["text_get"]; ?></p>
    <h2>POST Form Result:</h2>
    <p>text_post: <?php echo $_POST["text_post"]; ?></p>
    <h2>POST Form with GET Result:</h2>
    <p>text_get2: <?php echo $_GET["text_get2"]; ?></p>
    <p>text_post2: <?php echo $_POST["text_post2"]; ?></p>
    <h2>File Upload:</h2>
    <p>file:
    <pre><?php if ( ! empty( $_FILES ) ) {
            echo print_r( $_FILES, true );
        } ?></pre>
    </p>
    <p></p>
    </body>
    </html><?php
// Very Bottom of your code:
// Kill Post Form Data Session Variable, so User can reload the Page without sending post data twice
unset( $_SESSION["POST"] );

It only works to avoid the resubmit of $_POST, not $_GET. But this is the behaviour I need. The resubmit issue doesn't work with file uploads!

Seville answered 22/8, 2018 at 8:47 Comment(0)
P
0
if (($_SERVER['REQUEST_METHOD'] == 'POST') and (isset($_SESSION['uniq']))){
    if($everything_fine){
        unset($_SESSION['uniq']);
    }
}
else{
    $_SESSION['uniq'] = uniqid();
}

$everything_fine is the boolean result of form-validation. If the form is not validating then it shall be usually displayed again with a hint what to correct, so that the user can send it again. Therefore the $_SESSION['uniq'] is created again too if a corrected form is desired

Piss answered 30/10, 2018 at 21:16 Comment(4)
Please add some explanation to your answer such that others can learn from it - where does $everything_fine come from?Hardpan
@NicoHaase $everything_fine is the boolean result of form-validation. If the form is not validating then it shall be usually displayed again with a hint what to correct, so that the user can send it again. Therefore the $_SESSION['uniq'] is created again too if a corrected form is desired.Mikael
Please add all explanation to your answer by editing itHardpan
@NicoHaase It's not my answer, what I did describe is obvious in the code of the answer.Mikael
A
0

What Works For Me is :

if ( !refreshed()) {
   //Your Submit Here
        if (isset( $_GET['refresh'])) {
            setcookie("refresh",$_GET['refresh'], time() + (86400 * 5), "/");
        }

    }    
}


function refreshed()
{
    if (isset($_GET['refresh'])) {
        $token = $_GET['refresh'];
        if (isset($_COOKIE['refresh'])) {
            if ($_COOKIE['refresh'] != $token) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}  


function createToken($length) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

?>

And in your Form

 <form  action="?refresh=<?php echo createToken(3)?>">



 </form>
Ailbert answered 9/6, 2020 at 9:28 Comment(0)
M
0

This form.php sample shows how to use PRG correct (when form is valid or not).

  • It redirects to the same page only if form is valid and action was performed.
  • Redirection protects form from being resubmitted on page refresh.
  • It uses session to not lose success messages you want to show if form is valid.
  • There are two buttons for testing: "Valid submit", "Invalid submit". Try both and refresh page after that.
<?php
session_start();

function doSelfRedirect()
{
  header('Location:'.$_SERVER['PHP_SELF']);
  exit;
}

function setFlashMessage($msg)
{
  $_SESSION['message'] = $msg;
}

function getFlashMessage()
{
  if (!empty($_SESSION['message'])) {
    $msg = $_SESSION['message'];
    unset($_SESSION['message']);
  } else {
    $msg = null;
  }

  return $msg;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Validation primitive example.
  if (empty($_POST['valid'])) {
    $formIsValid = false;
    setFlashMessage('Invalid form submit');
  } else {
    $formIsValid = true;
  }

  if ($formIsValid) {
    // Perform any actions here.
    // ...

    // Cool!
    setFlashMessage('Form is valid. Action performed.');

    // Prevent form resubmission.
    doSelfRedirect();
  }
}
?>
<h1>Hello form</h1>

<?php if ($msg = getFlashMessage()): ?>
  <div><?= $msg ?></div>
<?php endif; ?>

<form method="post">
  <input type="text" name="foo" value="bar"><br><br>
  <button type="submit" name="invalid" value="0">Invalid submit</button>
  <button type="submit" name="valid" value="1">Valid submit</button>
</form>
Manslaughter answered 31/7, 2020 at 11:49 Comment(0)
D
-3

Why not just use the $_POST['submit'] variable as a logical statement in order to save whatever is in the form. You can always redirect to the same page (In case they refresh, and when they hit go back in the browser, the submit post variable wouldn't be set anymore. Just make sure your submit button has a name and id of submit.

Dowery answered 30/11, 2011 at 6:0 Comment(1)
Take a look at en.wikipedia.org/wiki/Post/Redirect/Get ! This is the right approachResile

© 2022 - 2024 — McMap. All rights reserved.