0

I completed my php code for throttling login, however now I want to use simple js or jquery code to get the throttling count down time from the php and make a live countdown.

Should I put the js script in the php file? or the html file? If so, how should I edit my code to work?

So far I have put the span id timer into the php which now shows the timer but again I dont get the php live timer

My php code:

<?php
include('database.php');
function get_multiple_rows($getfailed) {
    $rows = array();
    while($row = $getfailed->fetch_assoc()) {
        $rows[] = $row;
    }
    return $rows;
}
$throttle = array(1 => 1, 5 => 2, 10 => 30);
$getfailedq = "SELECT MAX(attempted) AS attempted FROM failed_logins";    
if ($getfailed = $mySQL->query($getfailedq)) {
    $rows = get_multiple_rows($getfailed);
    $getfailed->free();
    $latest_attempt = (int) date('U', strtotime($rows[0]['attempted'])); 
    $getfailedq = "SELECT COUNT(1) AS failed FROM failed_logins WHERE attempted > DATE_SUB(NOW(), INTERVAL 15 minute)";   
    if ($getfailed = $mySQL->query($getfailedq)) {
        $rows = get_multiple_rows($getfailed);
        $getfailed->free();
        $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 '<span id="timer">' . abs($remaining_delay) . '</span>';}                
                break;
            }
        }        
    }
}
?>

My js:

<script>
var count=30;
var counter=setInterval(timer, 1000); //1000 will  run it every 1 second
function timer(){
    count=count-1;
    if (count <= 0){
        clearInterval(counter);
        return;
    }
    document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}
</script>

1 Answer 1

1

You can initialize your JS variable by an PHP variable liek this:

var counter = <?php echo $counter; ?>;  

And create your counter in JS.

EDIT #1:
After initializing the variable you need to count it down.

var counter = <?php echo $counter; ?>;  
setInterval(function () {
    console.log(counter);
    counter--;
}, 1000 /*ms*/ );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.