Login and password system check date [PHP]

Asked

Viewed 279 times

-4

Good night!

I am working on a PHP project, and I came across a barrier, right at the end of my system:

It’s pretty simple even, it works like this:

1- ADMIN registers user, password and assigns an expiration date of the plan; (completed)

2 - USER comes across a login screen and password for access to the VIP panel; (completed)

3 - SYSTEM checks, based on the date that the ADMIN put to expire, whether the expiration date of the USER is greater than today’s date; (grabbed here)

Everything is already practically ready, what I lack is a way for the system to check, along with login and password, if the user’s expiration date > today’s date, if it is, it does not allow the user to log in and displays a message telling the user to contact an ADMIN.

I have no PHP course, the knowledge I have is all coming from Youtube and so I could not find any function to help me do this.

My login code and password:

<?php

include('conexao.php');  // conecta com o banco de dados

session_start(); // starta a sessão

$usuario = mysqli_real_escape_string($conexao, $_POST['usuario']);  // define a variável usuário como sendo aquilo que está dentro do post do formulário 


$senha = mysqli_real_escape_string($conexao, $_POST['senha']);  // define a váriavel senha como sendo aquilo que está dentro do post da senha


$query = "select * from usuarios where usuario = '{$usuario}' and senha = '{$senha}' ";  // query para selecionar tudo do banco de dados dos usuarios e verificar se possui um usuário e senha de fato

$result = mysqli_query($conexao, $query);   // faz a conexão da query com o banco de dados

$row = mysqli_num_rows($result);  // verifica o número de linhas encontradas


if($row == 1) {      // caso encontrada 1 linha, então o usuário está cadastrado

    
    
    $_SESSION['usuario'] = $usuario;    // se o usuário está cadastrado, inicia uma sessão com seu nome

    header('Location: conteudo');   // manda o usuário para a página do conteúdo VIP 

    

} else {       // se não está cadastrado
    $_SESSION['nao_autenticado'] = true;    // abre uma sessão nao autenticado
    header('Location: login.php');    //  volta o usuário para a página de login
    exit();     // finaliza
}  


?>

Things I tried to:

  • I tried to insert an Else if (I don’t know what it’s for, but it seems it’s an extra condition) along with the "check if there is a line", but I did not succeed, the page returned all wrong and blank, so I think it’s not even worth posting the code here.

  • I made the following code inside the VIP panel:

<?php

                  
                   include('conexao.php');

               
                  $sql="SELECT (data) from usuarios where usuario = '{$_SESSION['usuario']}'";
                  $result=mysqli_query($conexao,$sql);

                  while($mostrar=mysqli_fetch_array($result)){

                  ?>

                  <?php

                  $dt_atual = date("Y-m-d"); // data atual
                  $timestamp_dt_atual = strtotime($dt_atual); // converte para timestamp Unix
                   
                  $dt_expira = $mostrar['data']; // data de expiração do plano
                  $timestamp_dt_expira = strtotime($dt_expira); // converte para timestamp Unix
                   
                  // data atual é maior que a data de expiração
                  if ($timestamp_dt_atual > $timestamp_dt_expira){ // true
                    echo  "Plano Expirado!";
                    session_destroy();
                    header ('location: index.php');
                    session_start();
                    $_SESSION['expira'] = true;
                 }
                  else // false
                    echo "Seu Plano Está Ativo!";
  
                  ?>

This one even works, but the user gets direct access to the VIP panel and the information contained in it, and only when he updates that the system returns to the login page, I think it doesn’t work so.

Any answer helps me enough, maybe a function or something. Just missing this check for my system to work 100%, I am very grateful to the attention of all!!

Additional information:

  • I have no problem in mysql table that is saving users' data;
  • The mysql table is called users;
  • The mysql table contains: ID NAME CELLULAR PASSWORD EXPIRATION DATE of each user.

I forgot to mention that the problem in question is the fact that the user who has the expired plan, get access to the VIP panel in the same way as the user who paid on time.

An example:

John paid to use my system for 30 days, after these 30 days John can no longer have access to the VIP panel, so the system in question would check John’s date with today and only take John to the VIP panel if the ADMIN has renewed John’s plan for another 30 days.

    1. unnecessary session_destroy()... wipe the $_SESSION data or update it...... if you use $_SESSION['expires'], it should be placed BEFORE the redirect... as it is it will never be set.... include the DATA check along with the other code... leave everything in one place.... there are many more things to improve, but basically that’s it! hope I’ve helped...

1 answer

0


Well, I did a little extra research, I searched, I researched on Youtube and the like. I managed to make my system work perfectly... I believe it will now be the first solution to be available in the OS or any other similar forum.

I will leave the code commented below, any more questions about this system or something similar, I make available my email: [email protected] for contact!

Come on:

include('conexao.php');   // inclui a conexão com o banco de dados

session_start();   // starta a sessão


$datadehoje = date("Y-m-d"); // pega a data de hoje e insere na variável

$timestamp_dt_atual = strtotime($datadehoje);    // aqui transformamos a data de hoje em timestamp unix, um modelo padrão 


$usuario = mysqli_real_escape_string($conexao, $_POST['usuario']);  // pega o que tiver no post usuario e joga na variável usuario

$senha = mysqli_real_escape_string($conexao, $_POST['senha']); // pega o que tiver no post senha e joga na variável senha


$query = "select * from usuarios where usuario = '{$usuario}' and senha = '{$senha}' ";   // abre uma query, selecionando tudo dentro de usuários onde o usuario for o que tiver na variavel usuario ( ou seja, o que for digitado no post usuario )

$result = mysqli_query($conexao, $query);  // passa a conexão entre query e banco de dados

$row = mysqli_num_rows($result);    // faz a contagem do numero de rows (linhas) encontradas no result

if($row == 1){     // se tiver 1 linha ( ou seja, achou o usuário e senha correspondentes)

$sql= "SELECT (data) from usuarios where usuario = '$usuario'";  // vai selecionar a data do usuario que tiver na variavel
     
$sqlpassar = mysqli_query($conexao, $sql); // passamos a conexao entre a query novamente
    
$rowzinha = mysqli_fetch_array($sqlpassar);   // aqui vamos pegar o array da variavel anterior
     
$roz = $rowzinha['data'];   // vamos falar que a variavel $roz é o array da data, ou seja, vai selecionar a data daquele usuário

$timestamp_dt_expira = strtotime($roz);   // vamos converter novamente a variavel (roz) que guarda a data do usuário para timestamp unix


}else{                         // se não achar uma linha ( em possibilidade do usuario errar a senha, login ou similar ) 

    $_SESSION['nao_autenticado'] = true;    // abre uma sessão nao autenticado para o usuario

    header('Location: login.php');   // manda ele de volta para o login

    exit();   // finaliza
}

if ($timestamp_dt_expira > $timestamp_dt_atual){   // aqui continua o código, achando uma linha, ele vai conferir de a data de expiração é maior que a data atual, caso sim, então o usuário é permitido logar no sistema e acessar o conteúdo

     $_SESSION['usuario'] = $usuario;   // abre a sessão pro usuario
     header('Location: conteudo');    // manda ele pro conteudo
} else{     // se a data nao for maior ( ou seja, a data de expiração do usuário passou)
    $_SESSION['chamaradm'] = true;    // abre uma sessão novamente (dica: receba essa sessão na pagina de login com um alerta para o usuário contatar um adm e renovar o mes)
    header('Location: login.php');    // manda ele pra pagina de login
    exit();    // finaliza
}

There’s a lot wrong with the code, like I said, I’m not a professional programmer, but if the system’s function is to work, it works ;)

Thanks to all those who passed their eye on this topic and thought of something or even commented some help.

I went!!

Browser other questions tagged

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