Skip to content
Advertisement

limit a form submission – once in two minutes

I want to limit a form submission – once in two minutes
time of last attempt is in a session variable
something like this:

if(isset($_SESSION['last'])){
    $last = $_SESSION['last'];   
    $now = new DateTime("now");
    if($now < $last + 2min){
        echo 'SERVER IS BUSSY. TRY AFTER 2 MINUTES';
        $_SESSION['last'] = new DateTime("now");
        exit();
    }
}
else{
$_SESSION['last'] = new DateTime("now");
//continue with form data
}

pls help to write this code properly

Advertisement

Answer

Try something like this… Check the DateInterval class for more details.

$last = isset($_SESSION["last"]) ? new DateTime($_SESSION["last"]) : new DateTime("now");   
$now = new DateTime("now");
$diff = $last->diff($now);
if($diff->i < 2){
    $_SESSION["last"] = new DateTime("now");
    echo "SERVER IS BUSSY. TRY AFTER 2 MINUTES";
    exit();
}else{
    $_SESSION['last'] = new DateTime("now");
    echo "Continue with form data";
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement