我有一个PHP脚本,该脚本可处理条带付款并在成功交易后增加供体号。但是,脚本将增加2或有时增加3,而不是增加1。条带事务工作。我最好的理解是该页面以某种方式运行了两次。
捐赠者编号保存在.txt文件中。
页面上没有html。
LAMP堆栈。
<?php
ini_set('session.gc_maxlifetime',5);
session_set_cookie_params(5);
session_start();
$unsuccessful = false;
$paid = isset($_SESSION['number']);
//composer requirement for stripe sdk
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey("XXXXX");
// Get the payment token ID submitted by the form:
$amount = $_POST['amountInCents'];
$token = $_POST['stripeToken'];
try {
$charge = \Stripe\Charge::create([
"amount" => $amount,
"currency" => "usd",
"card" => $token,
"description" => "Business Name"
]);
} catch(Stripe_CardError $e) {
$unsuccessful = true;
// The card has been declined
}
if($unsuccessful == false){
#store current donor number in sessioncount.txt
$file = 'sessioncount.txt';
$current = (int)file_get_contents($file);
$new = $current;
if($paid === false){
$new = $current + 1;
}
$_SESSION['number'] = $new;
file_put_contents($file, $new);
header("Location:https://example.com/nextpage.php");
}
答案 0 :(得分:1)
在不多了解问题的情况下,是不可能知道导致重复执行的原因的原因。这个脚本怎么称呼?有人按下提交按钮吗?如果是这样,您是否在用户第一次单击提交按钮时将其禁用,以便仅在用户“双击”的情况下一次提交请求?这可能是对此类脚本进行双重处理的最常见原因。让我对用例了解更多,我可以提供更多帮助。
编辑:由于您现在已尝试禁用双重提交,请尝试使用此方法来帮助您进行调试。它可能无法完全解决问题,但是如果有多个请求并行命中脚本,则可以帮助您缩小范围:
<?php
ini_set('session.gc_maxlifetime',5);
session_set_cookie_params(5);
session_start();
$unsuccessful = false;
$paid = isset($_SESSION['number']);
//composer requirement for stripe sdk
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey("XXXXX");
// Get the payment token ID submitted by the form:
$amount = $_POST['amountInCents'];
$token = $_POST['stripeToken'];
if(!isset($_SESSION['processed'])) {
try {
$charge = \Stripe\Charge::create([
"amount" => $amount,
"currency" => "usd",
"card" => $token,
"description" => "Business Name"
]);
} catch(Stripe_CardError $e) {
$unsuccessful = true;
// The card has been declined
}
if($unsuccessful == false){
#store current donor number in sessioncount.txt
$file = 'sessioncount.txt';
$current = (int)file_get_contents($file);
$new = $current;
if($paid === false){
$new = $current + 1;
}
$_SESSION['number'] = $new;
file_put_contents($file, $new);
header("Location:https://example.com/nextpage.php");
$_SESSION['processed'] = true;
}
} else {
//Put some code here to help you troubleshoot, such as echoing an alert. If this code is executed, it means that something has externally triggered the execution of this script more than once.
}
如果这不起作用,则意味着对该文件的请求是并行进行的,并且脚本外部的某些行为导致该文件被多次执行。