How to avoid multiple access with the same login and password

Asked

Viewed 4,570 times

7

I would like to know how I can complement the code below so that if the user is logged in there is no other person to access the restricted area with the same login and password when the user who used that access is active. So that if it closes the browser or logout the section is destroyed thus freeing access to that account.

Along with placing a remember button on the login form panel.

Follows below the Mysql along with the codes.

Mysql

CREATE TABLE IF NOT EXISTS `membros` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `login` char(20) NOT NULL DEFAULT 'admin',
  `autor` varchar(20) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL DEFAULT 'Ryumaru',
  `senha` char(255) NOT NULL DEFAULT 'admin',
  `idade` int(2) NOT NULL DEFAULT '0',
  `email` varchar(255) NOT NULL DEFAULT '[email protected]',
  `cargo` enum('Adminstrador','Editor','Upload') NOT NULL DEFAULT 'Adminstrador',
  `data_cadastro` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `data_ultimo_login` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `arquivo_data_cad` date NOT NULL DEFAULT '2014-05-03',
  `arquivo_hora_cad` time NOT NULL DEFAULT '11:11:11',
  `ativado` enum('0','1') NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `membrosDados` (`id`,`login`,`senha`),
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

check.php

<?php

session_start();  // Inicia a session

include "config.php";

$login = $_POST['login'];
$senha = $_POST['senha'];

if((!$login) || (!$senha)){

    echo "<script>window.alert('Por favor, todos campos devem ser preenchidos!');</script>";
    include "index.php";

}
else{

    $senha = md5($senha);

    $sql = mysql_query("SELECT * FROM membros WHERE login='{$login}' AND senha='{$senha}' AND ativado='1'");
    $login_check = mysql_num_rows($sql);

    if($login_check > 0){

        while($row = mysql_fetch_array($sql)){

            foreach( $row AS $key => $val ){

                $$key = stripslashes( $val );

            }

            $_SESSION['id'] = $id;
            $_SESSION['login'] = $login;
            $_SESSION['autor'] = $autor;
            $_SESSION['email'] = $email;

            mysql_query("UPDATE membros SET data_ultimo_login = now() WHERE id ='{$id}'");

            header("Location:/admin/inicio/");

        }

    }
    else{

        echo "<script>window.alert('Acesso negado tente nova mente');</script>";

        include "index.php";

    }
}

?>

Function.php

<?php

function session_checker(){

    if(!isset($_SESSION['id'])){

        header ("Location:/admin/");

        exit(); 
    }
}

function verifica_email($EMAIL){

    list($User, $Domain) = explode("@", $EMAIL);
    $result = @checkdnsrr($Domain, 'MX');

    return($result);

}

?>

Protect the sections. by checking if the user is logged in I place this at the beginning of the page

<?php include("config.php");
session_start();
include "functions.php";
session_checker(); ?>

Logout.php

<?php

session_start();

if(!isset($_REQUEST['logmeout'])){

    echo "Voc&ecirc; realmente deseja sair da &aacute;rea restrita?<br />";
    echo "<a href=\"logout.php?logmeout\">Sim</a> | <a href=\"javascript:history.go(-1)\">N&atilde;o</a>";

}
else{
    session_destroy();


        include "index.php";


}
?>
  • Tried to put an active field in the database? When logging in, check if it is 1, this logged in, if not arrow 1 to leave as logged in.. if it is already with 1, it does not allow a new login, and when leaving, put the asset as zero, to release accesses... just need to see the question when close the browser, to do this automatically also.

  • This is exactly what I need in case the question of deleting if the page is closed for security or has in the case a length of time. I edited the question.

  • Try to do as I told you... to see, and here we will see if someone knows how to do when closing the browser, if it gives an active set = 0, to dislodge and free access to others

  • More in case only one doubt whether the user who logged in close the browser without undoing to apply the destruction of Session as well as update value 0 the user would not be prevented from entering in the same way as another user who is trying to use the same login and password ?

  • That’s what I told you... we have to see here with the staff if someone is able to help us try to solve... if it closes without leaving, I think we would have to give an active set 0, at the time of closing the browser... there must be some jquery that does this...

  • I think I found what I need look just http://answall.com/questions/33867/realizar-a%C3%A7%C3%A3o-to-close-browser

  • Okay, I guess that would be it...

  • I published a reply... if it is useful, give an acceptance. Thanks!

Show 3 more comments

4 answers

3


I thought what I wanted I appreciate everyone’s help I leave down the code in case anyone wants to use.

<?php
session_start(); 
// seta configurações  hora e tempo limite de inatividade//
date_default_timezone_set("Brazil/East");
$tempolimite = 900;
//fim das configurações de hora e limite de inatividade//

// aqui ta o seu script de autenticação no momento em que ele for validado você seta as configurações abaixo.//
// seta as configurações de tempo permitido para inatividade//
 $_SESSION['registro'] = time(); // armazena o momento em que autenticado //
 $_SESSION['limite'] = $tempolimite; // armazena o tempo limite sem atividade //
// fim das configurações de tempo inativo//
?>

Place the code below on the pages where you want to check the activity time.

<?php
    $registro = $_SESSION['registro'];
    $limite = $_SESSION['limite'];
    if($registro)// verifica se a session  registro esta ativa
    {
     $segundos = time()- $registro;
    }
    // fim da verificação da session registro

    /* verifica o tempo de inatividade 
    se ele tiver ficado mais de 900 segundos sem atividade ele destrói a session
    se não ele renova o tempo e ai é contado mais 900 segundos*/
    if($segundos>$limite)
    {
     session_destroy();
     die( "Sua seção expirou.");

    }
    else{
     $_SESSION['registro'] = time();
    }
    // fim da verificação de inatividade
    ?>

2

Create a field called ativo in your database, when logging in, seven as 1, and logging out seven as 0. Logged in, check if it is the ativo=1, you put the message: this user is already logged in, otherwise log in... And when closing the browser, use our colleague’s answer: Perform action when closing browser And seven ativo=0

1

My solution was very simple: Basically I did in the bank the following:

Alter Table usuarios add session_id varchar(255);

after every time the user logged in I did an update in the database via php:

UPDATE `usuarios` SET `session_id` = '" .session_id()."' WHERE `usuarios`.`id` = " . $resultado['id']

And then I added a php to all the pages as if it were a "Header" that checked if the user’s Session id was the same as the Session id that was currently in the database:

$result_auth = "SELECT * FROM usuarios WHERE id =" . $_SESSION['idUsuario'];
        $resultado_auth = mysqli_query($conn, $result_auth);
        $resultadoauth = mysqli_fetch_assoc($resultado_auth);
        if($resultadoauth['session_id']==session_id()){



        }else{

            header("Location: ". $urlproduto ."sair?voltou=true");

        }

Well, that solved for me, every time someone logs in and the account is already logged in session_id changes disconnecting who is already logged in!

I hope it helped, Abs!

  • 1

    It wouldn’t be interesting to say that someone is already logged in when trying to log in ?

1

guy 2 option puts a function on the login page that if you are already logged in sends to restricted page your.... or put in the database a new status field and have it checked when logging in... if it tries and is already logged in sends a message saying that it is already logged in another device

  • This I already understood in the case more as I asked above to André will give the problem asked above to him ?

Browser other questions tagged

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