gpt4 book ai didi

php - pdo连接在php函数中不起作用

转载 作者:行者123 更新时间:2023-11-29 21:04:33 27 4
gpt4 key购买 nike

我有这个用于限制登录的函数,但我有问题,pdo 连接在函数内部不起作用,它给我错误“未定义的 $conn 或调用 null 上的成员查询函数”,如果我是的,这是由于范围造成的,有什么解决办法吗?

<?php
function check(){
function get_multiple_rows($getfailed) {
$rows = array();
while($row = $getfailed->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $row;
}
return $rows;
}
$throttle = array(1 => 1, 5 => 2, 30 => 10);
if ($getfailed = $conn->query("SELECT MAX(attempted) AS attempted FROM failed_logins")){
$rows = get_multiple_rows($getfailed);
$getfailed->closeCursor();
$latest_attempt = (int) date('U', strtotime($rows[0]['attempted']));
if ($getfailed = $conn->query("SELECT COUNT(1) AS failed FROM failed_logins WHERE attempted > DATE_SUB(NOW(), INTERVAL 15 minute)")){
$rows = get_multiple_rows($getfailed);
$getfailed->closeCursor();
$failed_attempts = (int) $rows[0]['failed'];
krsort($throttle);
foreach ($throttle as $attempts => $delay){
if ($failed_attempts > $attempts) {
$remaining_delay = (time() - $latest_attempt) - $delay;
if ($remaining_delay < 0){
echo "You have exceeded the login attempts limit";
}
return false;
break;
}else{
return true;
}
}
}
}
}
?>

最佳答案

您可以尝试让您的检查函数接收如下参数:

<?php 
function check(PDO $conn){
function get_multiple_rows(PDOStatement $getfailed) {
$rows = array();
while($row = $getfailed->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $row;
}
return $rows;
}
$throttle = array(1 => 1, 5 => 2, 30 => 10);
if ($getfailed = $conn->query("SELECT MAX(attempted) AS attempted FROM failed_logins")){
$rows = get_multiple_rows($getfailed);
$getfailed->closeCursor();
$latest_attempt = (int) date('U', strtotime($rows[0]['attempted']));
if ($getfailed = $conn->query("SELECT COUNT(1) AS failed FROM failed_logins WHERE attempted > DATE_SUB(NOW(), INTERVAL 15 minute)")){
$rows = get_multiple_rows($getfailed);
$getfailed->closeCursor();
$failed_attempts = (int) $rows[0]['failed'];
krsort($throttle);
foreach ($throttle as $attempts => $delay){
if ($failed_attempts > $attempts) {
$remaining_delay = (time() - $latest_attempt) - $delay;
if ($remaining_delay < 0){
echo "You have exceeded the login attempts limit";
}
return false;
break;
}else{
return true;
}
}
}
}
}

现在您可以将 $conn 传递给您的函数,如下所示:

<?php
check($conn);

希望这有帮助...

关于php - pdo连接在php函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36935883/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com