【问题标题】:Prevent Ajax form double submitting using form tokens with php使用带有 php 的表单令牌防止 Ajax 表单重复提交
【发布时间】:2018-07-17 01:28:33
【问题描述】:

****更新****

我的代码似乎没有任何问题;因为使用完全相同的代码创建一个新文档完全有效。所以文件可能以某种方式损坏。见my answer below


我一生都找不到任何相关的问题或问题。 基本上,我有一个通过 Ajax 发送到 php 进程页面的评论表单。验证后,将数据插入 mySQL 数据库。 Ajax 向用户发送信息,主要是错误信息。我需要一种方法来防止在服务器端使用 php 进行多次提交。

我尝试过使用不使用 Ajax 的表单令牌,但不使用它。 $_SESSION 似乎没有延续到表单处理 php 页面。

问题... $_SESSION['review_form_token'] 根本不保存任何数据。如果我打印错误的会话数据,它根本不会打印任何东西!但是,我有一个使用会话的 php 验证码,它可以毫无问题地打印出来。当我在页面加载时设置会话时,它会按预期将令牌打印到隐藏输入中。我不明白为什么表单令牌没有传递给表单进程。 session_start() 在两个文档中。我试过ob_start() 无济于事。 请帮我调试一下。

这是我的简化设置...

index.php(在顶部):

<?php
session_start();
$reviewForm_token = md5(uniqid(rand(), true));
$_SESSION['review_form_token'] = $reviewForm_token;
?>

index.php - 表单(某处)

<form id="reviewform" method="post" novalidate>
   <input type="text" class="form-control form-style name" name="firstname" size="15" maxlength="40" autocomplete="given-name">
   <input type="text" class="form-control form-style name" name="lastname" size="15" maxlength="40" autocomplete="family-name">                 
    <textarea class="form-control form-style" name="review" minlength="50" required></textarea>                 
    <input type="text" class="form-control form-style" name="captcha" autocomplete="off" maxlength="6" required>
    <img src="https://via.placeholder.com/200x60" id="captcha-review" alt="Review captcha image" width="200" height="60">

    <input type="hidden" name="form_token" value="<?php echo $_SESSION['review_form_token']; ?>">
    <button type="submit" name="submit" class="btn btn-primary submit float-right font">Send</button>
    <button type="reset" class="btn btn-primary reset font">Reset</button>
</form> <!-- End form -->

index.php - Ajax(在文档底部)

$('#reviewform').submit(function(event) {
// Set some variables
var $this = this,
    firstnameInput = $('input[name=firstname]', $this),
    lastnameInput = $('input[name=lastname]', $this),
    nameInput = $('input.name', $this),
    ratingInput = $('input[name=StarRating]', $this),
    ratingInputChecked = $('input[name=StarRating]:checked', $this),
    stars = $('.star-rating', $this),
    reviewInput = $('textarea[name=review]', $this),
    captchaInput = $('input[name=captcha]', $this),
    form_tokenInput = $('input[name=form_token]', $this),
    submitButton = $("button.submit", $this);

// Get the form data
// Must relate to the name attribute...
var formData = {
    'firstname': firstnameInput.val(),
    'lastname': lastnameInput.val(),
    'StarRating': ratingInputChecked.val(),
    'review': reviewInput.val(),
    'captcha': captchaInput.val(),
    'form_token': form_tokenInput.val(),
};
// Process the form
$.ajax({
        type: 'POST', // Define the type of HTTP verb we want to use (POST for our form)
        url: 'formProcess-review.php', // The url where we want to POST
        data: formData, // Our data object
        dataType: 'json', // What type of data do we expect back from the server
        encode: true
    })
    .done(function(data) {
        // Here we will handle errors and validation messages
        if (!data.success) {

            // Handle errors for doublepost (form_token) ---------------
            if (data.errors.doublepost) {
                $('button', $this).parents('.form-row')
                    .append(label + data.errors.doublepost + '</label>')
                    .children('label.invalid').attr('id', 'doublepost-error');
            }
        } else {
            // SUCCESS!!
           // Thanks!
        }
    }); // End .done function
// Stop the form from submitting the normal way and refreshing the page
event.preventDefault();
}); // End .submit function

formProcess-review.php

<?php
session_start();
$errors     = array(); // array to hold validation errors
$data       = array(); // array to pass back data
$firstname  = $_POST['firstname'];
$lastname   = $_POST['lastname'];
$StarRating = $_POST['StarRating'];
$review     = $_POST['review'];
$captcha    = $_POST['captcha'];

// Form Validation...

if ($_POST['form_token'] !== $_SESSION['review_form_token']) {
   $errors['doublepost'] = 'You have already submitted your review, you can not resubmit. If you need to send another review, please reload the page.';
}
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
   // if there are items in our errors array, return those errors
   $data['success'] = false;
   $data['errors']  = $errors;
} else {
   // if there are no errors process our form, then return a message

   unset($_SESSION['review_form_token']);

   // mySQL inserting data...

   // show a message of success and provide a true success variable
   $data['success'] = true;
   $data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
?>

【问题讨论】:

  • 您是否尝试过在 formProcess-review 中的 session_start 之后使用调试器或转储 $_SESSION?
  • else{} 添加到if ($_POST['form_token'] !== $_SESSION['review_form_token']) {...} 时会发生什么?或者你已经有一个了?使用php的报错,看源码和开发者控制台。
  • @Devon 使用 foreach 循环我可以转储可用会话,其中令牌不属于其中。只有验证码会话被转储。
  • @FunkFortyNiner 老实说,这不是正确的很多,仍然无法正常工作。并且错误报告也没有显示任何内容。我是否做得正确是另一回事,我以这个答案为指导:stackoverflow.com/a/21429652/2358222
  • 所有可用会话是什么意思,为什么要使用 foreach 循环?你就不能var_dump($_SESSION)吗?

标签: php jquery ajax forms session-variables


【解决方案1】:

我刚刚尝试了您的代码,并且 Form TokenSession 令牌 都在您的 formProcess-review.php 中正确捕获。您的代码必须有其他导致它的问题。

简化的 Ajax 提交。

$.ajax({
        type: 'POST', 
        url: 'formProcess-review.php', 
        data: formData, 
        dataType: 'json', 
        encode: true
    })
    .done(function(data) {
  		alert(data.message);
      
    });

简化形式Process-review.php

<?php
session_start();
$data['message'] = "Form token = ".$_POST['form_token']."   Session value = ".$_SESSION['review_form_token'];
echo json_encode($data);
die();
?>

【讨论】:

  • 很高兴知道有人可以让它工作。但是,我刚刚用上面的代码替换了我的所有代码,我无法获得$_SESSION 的值。也许它与我拥有的服务器有关??
  • 尝试使用不同的浏览器
  • 巧合的是,我创建了一个新页面并尝试了您的代码,并且成功了。所以现在我需要弄清楚是什么导致它出现故障。
  • 很高兴知道。祝你好运
【解决方案2】:

尝试将此选项“withCredentials”添加到 ajax 调用中:

$.ajax({
    type: 'POST', 
    url: 'formProcess-review.php', 
    data: formData, 
    dataType: 'json', 
    encode: true,
    xhrFields: {
      withCredentials: true
    }
}

可能是ajax调用没有将会话cookie发送到服务器。

【讨论】:

  • 不幸的是,使用withCredentials 不起作用。
【解决方案3】:

jun drie's anwser 激励我用相同的代码创建一个全新的 index.php;这似乎奏效了。我不知道为什么或如何,但原始文件一定已经损坏,迫使它无法正常工作,但仍然让它出现在网络上(奇怪,嗯?!)

我已经编辑了我的代码,使其更简单,希望更好。

我在取消设置会话时遇到了麻烦,所以我现在在 index.php 中的 session_start(); 之后直接调用 session_unset(); 以取消设置从 1 次重新加载之前的任何以前的会话。

虽然我做了这个改变,但很奇怪以前没有它也能正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-04
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    相关资源
    最近更新 更多