How to put a timeout or disable a button by time set in PHP or Javascript?

0

First, excuse the context of the question seems very repetitive but it is not.

Well, I wanted to know if it's possible to put a timeout on a button on my standalone web page of the person you're visiting. When clicking, another person can only click again after 1 hour. Is it feasible to do this without the need for a DB?

I searched, but I could not solve it, so I decided to ask.

    
asked by anonymous 20.04.2018 / 13:03

2 answers

1

No library

NOTE: For you not to wait for 1 hour, in the test in the example above I put 2 minutes although it appears in the button when the time is disabled in relation to 1 hour.

//pega dados do arquivo
$result=file_get_contents("timerdobotao.txt");

//Unix timestamp data atual
$timestamp = time();

//diferença entra as datas
$unixDif = $timestamp-$result;

//minutos que faltam para ativar o botão
$minFaltam =(int)(60-($unixDif/60));

if(isset($_POST['click']))
{
    //salva timastamp da data atual no arquivo
    file_put_contents("timerdobotao.txt", $timestamp);
}

if ($minFaltam<0){
    //salva timastamp da data atual no arquivo
    file_put_contents("timerdobotao.txt", $timestamp);

    echo "<form action='' method='post'>
      <button type='submit' name='click' class='click'>Entrar</button>
    </form>";

}else{

  echo "<button type='button' class='entrar' disabled>Acesso para 1º usuario a clicar aqui em ".$minFaltam." min</button>";
}

With Jquery

  

To test 3 minutes of access for the first user to click on the Entrar

  • If access is enabled, the first person who clicks the Entrar button will have access to the page by 60 minutos or that indicated in the variable $tempoConcedido at the beginning of the code.
  • Other users will see in a message with a countdown the remaining time to access the page, and at the end of the count this message becomes the Entrar button to be able to try to access since the first one to click enters and blocks the access of the others.

    <?php
    
    $timestamp="";
    $timestamp="";
    
    //tempo em minutos para habilitar novo acesso
    $tempoConcedido=3;
    
    //arquivo que irá conter o timestamp para uso nos calculos do script
    $filename = "timestamp.txt";
    
    //Unix timestamp data atual
    $timestamp = time();
    
    //se o arquivo existir calcula quantos minutos faltam para liberar novo acesso
    if (file_exists($filename)) {
        //pega dados do arquivo
        $result=file_get_contents($filename);
    
        //diferença entra os timestamps
        $unixDif = $timestamp-$result;
    
        $unixDifMinutos = ($unixDif/60);
    
        //minutos que faltam para ativar o botão
        $minFaltam = (int)($tempoConcedido-$unixDifMinutos);    
    
    }else{
    
        $minFaltam=0;
    
    }
    
    //se o cookie não existir executa o codigo abaixo
    if (!isset($_COOKIE["acessoLivre"])){
    
        if ($minFaltam<=0){
    
            if(isset($_POST['click'])){
                //salva timastamp da data atual no arquivo
                file_put_contents($filename, $timestamp);
                setcookie('acessoLivre', 'umaHora', (time() + (1 * 120)));
                header('Location: contdown-desabilita-botao.php');
                exit();
            }
    
            echo "<form action='' method='post'>
              <button type='submit' name='click' class='click'>Entrar</button>
            </form>";
    
        }else{
    
            echo "<div id='desabilitado'><form action='' method='post'><button type='button' class='entrar' disabled>Acesso para 1º usuario a clicar aqui em <span id='time'></span></button></form></div>";    
        }
    }
    
    //mostra o tempo que falta para outro usuario poder acessar a página
    if ($minFaltam>0){
    
    ?>
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scripttype="text/javascript">
    
        function startTimer(duration, display) {
            var timer = duration,
                minutes, seconds;
    
            interval = setInterval(function() {
                minutes = parseInt(timer / 60, 10)
                seconds = parseInt(timer % 60, 10);
    
                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;
    
                display.text(minutes + ":" + seconds);
    
                if (--timer < 0) {
                    //muda a div que contem o botão com contador regressivo para o botão de acesso
                    $('#desabilitado').html('<form action="" method="post"><button type="submit" name="click" class="click">Entrar</button></form>');
                    $("#registration-form").submit()
                    clearInterval(interval);
                }
            }, 1000);
    
            return new Date();
        }
    
        jQuery(function($) {
            s = <?php echo $minFaltam ?>;
            var Minutes = 60 * s,
                display = $('#time');
    
            var startDate = startTimer(Minutes, display);  
    
        });
    
        </script>
    
    <?php
    }
    ?>
    
    <?php
    if (isset($_COOKIE["acessoLivre"])){
        echo "<h1>Pagina liberada</h1>";
    
        echo ($_COOKIE["acessoLivre"]);
    }
    ?>
    
20.04.2018 / 22:15
1

File clickado.php

<?php
    $time = time();
    $usuario = $_POST['usuario'];
    $fp = fopen("timerdobotao.txt", "w+");
    $escreve = fwrite($fp, $time);
    fclose($fp);
?>

Verify

<?php
   $arquivo = fopen ('timerdobotao.txt', 'r');
   $rt = "false";
   while(!feof($arquivo)){
     $linha = fgets($arquivo, 1024);
     if($linha !=""){
        if($linha < (time() - (1 * 60 * 60))){ // horas * minutos * segundos
           $rt = "true";
        }
     }
   }
echo $rt;
?>

In your html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script>functionClickDoBotao(){varusuario="idDoUsuario";
       $.post("clickado.php",{usuario:usuario}function(){

       })
   }
   setInterval(function(){
      var usuario = "idDoUsuario";
      setInterval(function(){
         $.get("verificabotao.php",{usuario:usuario},function(rt){
            if(rt == "true"){
                $("#meuBotao").prop("disabled",false);
            }else{
                $("#meuBotao").prop("disabled",true);
            }
         });
      }, 5000);
   });
</script>

Make a button and assign an id

<button onclick="ClickDoBotao()" id="meuBotao">

I did not have to test the code but the logic is this

    
20.04.2018 / 13:44