在 PHP 中如何防止提交表單時進行重複插入?


可以透過 PHP 會話來防止在提交表單時進行重複插入。PHP 會話會設定會話變數(例如 $_SESSION['posttimer']),用以設定 POST 的當前時間戳。在 PHP 中處理表單之前,會檢查 $_SESSION['posttimer'] 的存在和特定時間戳差值(例如 2 或 3 秒)。透過這種方式,可以識別和刪除那些實際上是重複的插入。

簡單表單 −

// form.html
<form action="my_session_file.php" method="post">
   <input type="text" name="bar" />
   <input type="submit" value="Save">
</form>

與上面的 'my_session_file.php' 關聯的程式碼 −

示例

if (isset($_POST) && !empty($_POST)) {
   if (isset($_SESSION['posttimer'])) {
      if ( (time() - $_SESSION['posttimer']) <= 2) {
         // less then 2 seconds since last post
      } else {
         // more than 2 seconds since last post
      }
   }
   $_SESSION['posttimer'] = time();
}

輸出

這會生成以下輸出 −

The unique form submitted data.

posttimer 會話變數已被設定,當上次 POST 操作之前的時間差為 2 秒或更短時,可以將它刪除。否則將其儲存。time 函式會被呼叫,且值會被賦予 posttimer 會話變數。

更新於:2020-04-09

2 千次瀏覽

開啟你的 職業生涯

透過完成課程進行認證

開始
廣告