Home >Backend Development >PHP Tutorial >How to prevent users from refreshing and submitting repeatedly in php

How to prevent users from refreshing and submitting repeatedly in php

WBOY
WBOYOriginal
2016-07-25 09:00:131070browse
In terms of preventing users from refreshing, the method of immediately destroying $_POST['name'] does not work. This method may fail due to caching. This article uses session to solve the problem. Friends in need can refer to it.

Session is saved on the server side. After the value of the Session variable is changed in the PHP process, it is saved on the server side. The next time you access this variable, you will get the newly assigned value. Therefore, you can use a Session variable to record the number of form submissions. , when it is greater than 1, the data in the form will not be processed.

Test code:
<?php
/**
 * 防止刷新 重复提交
* site bbs.it-home.org
*/
if (isset($_POST['action']) && $_POST['action'] == 'submitted') {  
      session_start();  
      isset($_SESSION['submit_time']) or die ("no session");  
      if ($_SESSION['submit_time']==0){  
              print '<pre class="brush:php;toolbar:false">';  
        
              print_r($_POST);  
              print 'Please try again';  
        
              print '
'; $_SESSION['submit_time']=1; echo $_SESSION['submit_time']; } else { print '
';  
        
              print_r($_POST);  
              echo "However you have submitted";  
              print '
'; } } else { session_start() or dir("session is not started"); $_SESSION['submit_time']= 0; // isset($_SESSION['submit_time']) or die ("session var is not created"); // echo $_SESSION['submit_time']; ?>
Name:
Email:
Beer:

The above code has a shortcoming: Without explicitly destroying the Session, expired Session files may still remain in the server file system. If anyone has a good method, please share it.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn