Prevent user to use back button with warning or disable any insert

前端 未结 2 1087
-上瘾入骨i
-上瘾入骨i 2020-12-20 10:25

I have a form in page1.php which directs to page2.php from where the data from the form in page1.php is inserted into database. after

相关标签:
2条回答
  • 2020-12-20 10:36

    Instead of giving link to a third page, redirect to the very same URI
    this is quite handy method called POST/Redirect/GET:
    here is a concise example of it:

    <?php  
    if ($_SERVER['REQUEST_METHOD']=='POST') {  
    
      $err = array();
      //performing all validations and raising corresponding errors
      if (empty($_POST['name'])) $err[] = "Username field is required";  
      if (empty($_POST['text'])) $err[] = "Comments field is required";  
    
      if (!$err) {  
        //if no errors - saving data and redirect
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
      }  else {
        // all field values should be escaped according to HTML standard
        foreach ($_POST as $key => $val) {
          $form[$key] = htmlspecialchars($val);
        }
      }
    } else {
      $form['name'] = $form['comments'] = '';  
    }
    include 'form.tpl.php';
    ?>  
    

    Here you can see another example, concise yet powerful: Separating Logic/Style in PHP properly
    it's complete solution to display, add and edit database contents, exactly for admin purpose.

    0 讨论(0)
  • 2020-12-20 10:44

    You should not display your message on page2.php.

    Instead :

    • page2.php should deal with the data
    • when the data has been saved, page2.php should redirect to confirmation.php
    • And it's only confirmation.php which would display the message.


    For more informations, take a look at the Post/Redirect/Get pattern.


    Edit after the comment : but note that, in any case, you will never be able to prevent the user from re-submitting a form, if he really wants to...

    The only solution you'll have is, when a form is submitted, to check in your database if the currently submitted data already exists -- and if it does, refuse to insert it again.

    Of course, if the suer changes even a single letter in his input, it won't be the same data anymore...

    0 讨论(0)
提交回复
热议问题