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

Asked

Viewed 1,372 times

-1

Guys, first excuse the context of the question seems very repetitive but it’s not.

Well I was wondering if it’s possible to put one timeout on a button of my web page independent of the person accessing. By clicking, another person will only be able to click again after 1 hour. It is feasible to do this without the need for a BD?

I’ve been doing some research but I couldn’t solve it, so I thought I’d ask.

  • You’re talking about two people on different computers, interfering with each other’s button without the need for BD?

  • Yes, for example button 1 is active, and someone clicked, so others can only click after one hour. Under these conditions the button would be disabled on my server (in the code). So there is no need for a BD, it is possible?

  • No database connection, I don’t think it’s possible.

  • 1

    well you can generate a txt file ai check the time pressing from there

  • Okay Marcos, it’s a really great idea, but how exactly would I do it?

  • 1

    You can use a real time structure, this way in each access of a new user, creates a session on the server. I recommend the use of Nodejs with Socket io..

  • I added an answer, more or less the logic is this, but I had no way to test here

  • I added my answer option with Jquery.

Show 3 more comments

2 answers

1


Library-less

NOTE: For you not to be waiting 1 hour, in the test in the example above I put 2 minutes despite appearing on the button when disabled the time relative 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 the button Entrar

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

    <?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>
    
        <script type="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"]);
    }
    ?>
    

1

Filing cabinet clickado.php

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

Filing cabinet php check.

<?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>
   function ClickDoBotao(){
       var usuario = "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>

Cire a button and assign an id

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

Obs had no way to test the code but the logic is this

  • It didn’t work here with me.

  • It didn’t work here either, but I’m trying to solve, the logic was good, I think you have error capturing the txt time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.