我正在开发一个 PHP 应用程序,用户可以在其中请求 OTP(一次性密码)进行身份验证。我想实施一项限制,即仅允许用户在 5 分钟内最多发送 5 个 OTP 请求。 如果用户在过去 5 分钟内已生成 5 个 OTP,则希望限制用户在上次生成的 OTP 请求之后的接下来 5 分钟内。
这是我迄今为止尝试过的:
我的数据库中有一个表 (mobile_otp_verification),用于存储 OTP 请求,包括 user_id、电子邮件、otp 和 generated_at 时间戳。
我编写了一个 PHP 函数 is_otp_limit_exceed 来检查用户是否超出了 OTP 请求限制。这是函数:
function is_otp_limit_exceed() {
$maxRequestsPerHour = 5; // Maximum number of requests allowed per hour
$lockoutDuration = 300; // Lockout duration in seconds after exceeding the limit (1 hour)
global $CFG, $DB;
$query = "SELECT COUNT(*) AS total_records, MAX(generated_at) AS earliest_record, NOW() as cTime
FROM mdl_mobile_otp_verification_wtc
WHERE user_id = 1 AND generated_at > DATE_SUB(NOW(), INTERVAL ".$lockoutDuration." SECOND)";
$countResult = $DB->get_records_sql($query);
if (!empty($countResult)) {
$firstElement = reset($countResult);
$currentTime = $firstElement->ctime;
$totalRecords = $firstElement->total_records;
$earliestRecord = $firstElement->earliest_record;
}else {
$currentTime = null;
$totalRecords = 0;
}
$earliestRecord = strtotime($earliestRecord);
$currentTime = strtotime($currentTime);
$time_elapsed_since_last_otp = $current_time - $last_generated_at;
if ($totalRecords >= $maxRequestsPerHour && $time_elapsed_since_last_otp < $lockoutDuration) {
return 'limit exceed';
}
send_otp(); // function to send otp
}
但是,我正在努力实现逻辑以强制执行 5 分钟内 5 个 OTP 请求的限制。有人可以帮助我理解逻辑或提供如何实现这一目标的建议吗? 即使我限制接下来的 5 分钟,用户仍然可以发送 OTP。
如果我正确理解您的要求,如果用户在 5 分钟内触发了 5 个 OTP,您希望阻止用户生成 OTP 额外 5 分钟。
在这种情况下,请
$lockoutDuration0 = 600;
$lockoutDuration1 = 300;
将您的查询更改为
$query = "SELECT COUNT(*) AS total_records, MAX(generated_at) AS earliest_record, NOW() as cTime
FROM mdl_mobile_otp_verification_wtc
WHERE user_id = 1 AND generated_at > DATE_SUB(NOW(), INTERVAL ".$lockoutDuration0." SECOND)
AND generated_at < DATE_SUB(NOW(), INTERVAL ".$lockoutDuration1." SECOND)
";
在这种情况下,系统将检查用户在过去 10 分钟的前 5 分钟内触发的 OTP 数量是否正确,其余代码将完成这项工作