Register user's date, time and IP in Login

0

Hello, I have a problem in which I can not find a solution (and I'm still a layman in PHP to help), I've reviewed the internet and found nothing that could help me, I have a PHP login page where checks if the user exists in a table, if it exists it sends it to a restricted page, if it does not reload the page giving an incorrect login alert or password. I would like to know if it is possible if the login is correct to register in the same table the user's time, login and ip.

Login page code:

<?php
    include "config/cabecalho.php";
?>
        <?php
            if(isset($_SESSION['msg'])){
                echo $_SESSION['msg'];
                unset($_SESSION['msg']);
            }
        ?>
<body>
<header>
</header>

<font class="titulo-login"><b>ACESSO RESTRITO</b></font>

        <div class="login-pagina">
        <div class="caixa-login">

            <form action="abrir_interno.php" method="post" name="formlogin" id="formlogin">
                <br>
                <br>
                <h1>E-MAIL</h1>
                <br>
                <img src="imagens/iconeavatar.png" class="img-login" />
                <input type="text" name="email" id="email" class="campo-login" placeholder="EMAIL" required autofocus/>
                <br>
                <br>
                <h1>SENHA</h1>
                <br>
                <img src="imagens/iconecadeado.png" class="img-login"/>
                <input type="password" name="senha" id="senha" class="campo-login" placeholder="Senha" required/><br /><br />
                <input type="submit" name="Submit" value="ENTRAR" class="botao">
            </form>
        <br>
      <br>
</div>
<button class="botao-admin" onclick="location.href='index.php'"><img src="imagens/iconevoltar.png" class="img-botao">VOLTAR PARA ÁREA DE CLIENTES</button>

</div>

<?php
include "config/rodape.php";
?>


    </body>

Page code "open_internal.php"

<?php 
// session_start inicia a sessão
session_start();
// as variáveis login e senha recebem os dados digitados na página anterior
$login = addslashes($_POST['email']);
$senha = addslashes($_POST['senha']);
// a próxima linha é responsável em se conectar com o banco de dados.

    include "config/conexao.php";

$sql = "SELECT * FROM usuario_interno WHERE NOME = '$login' AND SENHA= '$senha'";

// A variavel $buscar pega o $login e $senha, faz uma pesquisa na tabela de usuarios

$buscar = mysqli_query($conexao,$sql) or die (mysqli_error($conexao));

if(mysqli_num_rows($buscar)>0)
{
$_SESSION['email'] = $login;
$_SESSION['senha'] = $senha;
header("location:../restrito/restrito_painel.php");  
}else{
    unset ($_SESSION['email']);
    unset ($_SESSION['senha']);
    echo'';
    header("refresh: 0; url=../acesso_interno.php");
    echo '<script type="text/javascript">
    alert("Erro ao entrar!\n LOGIN ou SENHA incorretos!")
    </script>';

    };

?>

I would like to know if in this open_internal.php it would be possible to register the user's date, time and IP and, if possible, what would happen?

Internal user table:

Tablestructure:

Thanks for all the help right away!

Ps: If my code has something wrong, please correct me: D

    
asked by anonymous 14.02.2018 / 17:50

1 answer

0

Add a UPDATE table ... after if(mysqli_num_rows($buscar)>0) or create a procedure to check the login or use the multi_query > of MySQLI . Ex:

MySQL

/* Opcional */
CREATE TABLE 'users' (
    'id' INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    'user' VARCHAR(32) NOT NULL,
    'password' VARCHAR(128) NOT NULL
);

/* Adapte conforme sua tabela */

DELIMITER $$
CREATE PROCEDURE checkLogin(IN userName VARCHAR(255), IN pass VARCHAR(255), OUT userId INT)
BEGIN
    SELECT 'id' INTO userId FROM 'users' WHERE 'user' = userName AND 'password' = pass;

    UPDATE 'users' SET 'last_access' = IF(userId > 0, NOW(), "") WHERE 'id' = userId;

END $$

DELIMITER ;

/* Opcional */

INSERT INTO 'users' VALUES (null, "valdeir", "123456");
INSERT INTO 'users' VALUES (null, "valdeir.psr", "1234");

PHP:

<?php

/* Conecta no servidor */    
$conn = new MySQLi("localhost:3307", "root", "123456", "teste");

$user = "valdeir";
$pass = "123456";

/* Executa múltiplas "queries" */
$conn->multi_query("CALL checkLogin(\"{$user}\", \"{$pass}\", @userId); SELECT @userId AS userId;");

/* Acessa o resultado do SELECT */
$conn->next_result();
$result = $conn->store_result();

var_dump( $result->fetch_object() );

PHP without "Procedures":

<?php

$conn = new MySQLi("localhost:3307", "root", "123456", "teste");

$user = "valdeir";
$pass = "123456";

$queries = <<<SQL
SELECT @userId := 'id' AS userId FROM 'users' WHERE 'user' = "{$user}" AND 'password' = "{$pass}";
UPDATE 'users' SET 'last_access' = IF(userId > 0, NOW(), "") WHERE 'id' = userId;
SQL;

if ($conn->multi_query($queries)) {
    $result = $conn->store_result();

    var_dump( $result->fetch_object() );
} else {
    die( $conn->error );
}
  

To catch IP use the global variable $_SERVER["REMOTE_ADDR"]

    
14.02.2018 / 19:09