使用php使用表单令牌防止Ajax表单双重提交

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (308)

**** ****更新

我的代码似乎没有任何问题; 因为创建一个完全相同的完全相同的代码的新文档。所以文件可能会以某种方式变得腐败。请参阅下面的答案

我不能为我的生活找到任何相关的问题或问题。基本上,我有一个通过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);
?>
提问于
用户回答回答于

尝试将此选项'withCredentials'添加到ajax调用:

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

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

用户回答回答于

我刚刚尝试了您的代码,并且在formProcess-review.php上正确捕获了表单令牌会话令牌。你的代码必须有其他导致它的问题。

简化的Ajax提交。

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

简化formProcess-review.php

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

扫码关注云+社区

领取腾讯云代金券