我有用于限制登录的函数,但是我有问题,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;
}
}
}
}
}
?>
最佳答案
您可以尝试使您的check Function接收如下参数:
<?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传递给Function:
<?php
check($conn);
希望这可以帮助...
关于php - pdo连接在php功能中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36935883/