Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

258
Visualizações
How to avoid double login in PHP?

I am creating a system where the objective is that only one person per user can access the system, for this I have in my DB two tables called: users and accesses What I am doing is that when person 1 logs in, it is saved in my DB the id of the session in the two tables, if person 2 with the same user tries to access then the first person to log in takes it out of the system. I do this with help with AJAX, comparing if the last user who started has the same session id then he can navigate without problem, if he does not close session.

The problem is that I make this ajax request every 10s, but I would have problems if 10,000 people or more log in, then the request will be sent to the server every 10 seconds and this could saturate the server.

Try an active field if the session is equal to 1 and if the session is equal to 0, then discard this since if the user closes the browser then I never close session and the person will not be able to access, I also tried using a ajax method to detect if you close the browser but it is not very reliable. Has anyone had the same problem? I would thank you a lot.

I leave my php and js code to display as I do:

Code JS:

 $(function() { 
    cron(); // Lanzo cron la primera vez
    function cron() {
         $.ajax({
          method: "POST",
          url: "closeuser.php", 
          data: { action: 1 }
          })
        .done(function(msg) {
            var trimmedString = msg.trim();
            console.log(trimmedString)
          if( trimmedString == 'success' ) {  // Valida si el server devolvió 'success'
                 location.href='logoutuser.php';
          }
        });
    }
    setInterval(function() {
        cron();
    }, 10000); // cada 10 segundos
});

Code PHP:

<?php

    require_once 'Connections/sesionunica.php';
    $connection_s = new sesionunica();
    
     if(!isset($_SESSION["id_user"])){ 
            echo"<script>location.href='index.php';</script>";  
        } 
    
    if(isset($_POST["action"])) { // Se pasa una acción
        switch(sprintf("%d", $_POST["action"])) { // ¿Qué acción?
            case 1:
                cerrar();
                break;
            default:
            echo "default";
        }
    }
    function cerrar(){
        $ses = session_id();
        $connection_s = new sesionunica();
        $userById = $connection_s->getUsers($_SESSION["id_user"]);
        if ($userById["id_sesion"] <> $ses) {
        echo "success"; 
        }
    }
    
    ?>

In the same way, I cannot use websockets since there are accessibility problems with the server.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think you could create an "access filter" that would check if the "access token" is valid or not in every request the users would make.

If the "access token" is expired, then return an HTTP status 401 (unauthorized), and, in client-side, redirect the user to login page.

Request filter is a very common resource that many REST frameworks have.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda