Redirect system

Asked

Viewed 27 times

0

Good morning guys, a problem that I have not been able to solve so far consists of a login system, where if, for example, the user has already logged in and has not clicked on "QUIT" (logout), if it closes and re-accesses the site, it would be redirected to the user page. When I do not use the condition of checking if the person is classified as "ADMIN", apparently everything goes well. However, by adding the additional condition of making this check, it is not working.

<?php
    require_once 'classes/db_connect.php';
    session_start();

if(isset($_SESSION['login']) && $_REQUEST['admin'] == '0') {
    header('Location: areaUsuario.php');
} else if (isset($_SESSION['login']) && $_REQUEST['admin'] == '1') {
    header('Location: areaAdm.php');
}

if(isset($_POST['submit'])):
        $erros = array();
        $username = mysqli_escape_string($connect, $_POST['email']);
        $password = mysqli_escape_string($connect, $_POST['senha']);
        $admin = $_REQUEST['admin'];

        if(empty($username) or empty($password)):
            $erros[] = "<li>Todos os campos devem ser preenchidos.</li>";
        else:
            $sql = "SELECT username FROM user WHERE username = '$username'";
            $resultado = mysqli_query($connect, $sql);

            if(mysqli_num_rows($resultado) > 0):
            $password = md5($password);
            $sql = "SELECT * FROM user WHERE username = '$username' AND password = '$password'";
            $resultado = mysqli_query($connect, $sql);

            if(mysqli_num_rows($resultado) == 1):
                $dados = mysqli_fetch_assoc($resultado);
                if ($dados['admin'] == '1'):
                    mysqli_close($connect);
                    $_SESSION['login'] = $username;
                    $_SESSION['senha'] = $password;
                    $_SESSION['admin'] = $admin;
                    header('Location: areaAdm.php');

                else:
                     mysqli_close($connect);
                    $_SESSION['login'] = $username;
                    $_SESSION['senha'] = $password;
                    $_SESSION['admin'] = $admin;
                    header('Location: areaUsuario.php');
                endif;

                else:
                    $erros[]="<li>Usuário e senha não conferem</li>";
                endif;
            else:
                $erros[]="<li>Usuário não cadastrado</li>";
            endif;
    endif;
endif;
?>
?>
  • this variable 'admin' is coming as? via post? has the superglobal _POST as well. Who knows it must be around that this information is coming... Another idea is since the superglobal _Session is also storing login information, why not store information whether it is admin or not? finally just an idea.

  • Admin is coming from the database, like 1 or 0. The request does not work in this sense?

  • The attempt to perform with SESSION to "admin" also did not go well.

  • Looking at the php documentation, I saw a comment below showing the difference between methods _GET, _POST and _REQUEST... from a look -> https://www.php.net/manual/en/reserved.variables.request.php

1 answer

1

Ancient answer->

Notei que no inicio chamou a classe do db, e provavelmente lá é feito o request para ver se o usuário é admin ou não, MAS... como ele vai fazer o request se ele ainda nem sabe quem é que ta logado? 

A `session_start()` esta vindo depois da chamada da classe.. ou seja se na classe houver um `_SESSION['login']` vai dar `null`... e por fim nao vai fazer o request corretamente...


Tente mover o `session_start` para cima e veja se funciona.


Caso não funcione ainda, seria interessante nao alterar a superglobal `_REQUEST` e continuar usando a superglobal `_SESSION` para guardar informações de logon..
Ao fazer logoff ela é facilmente destruida com `session_destroy` então acho que seria bacana utiliza-la.

New Answer->

For me to stay in the same tune as you are trying to imagine more clearly your intention is "Do not need to re-log in if the user has not yet clicked out". Then we get into a problem.

Session only exists in one section, if you close this section it obviously ends.

Localstorage lasts longer the information in the browser. It is possible to arrow it and update it in the frontend with js.

Localstorage does not exist in PHP.

When you open the login screen the first thing you have to do is actually check if it was already logged in, and for that you need information on the Log in.

You can in the frontend take this information from localStorage and pass in ajax via post method to the backend..

//setar o local storage só depois de fazer login
var permisao= 0
var loginDoUsuario = 'joaoDaNika'
localStorage.setItem('admin', permisao)
localStorage.setItem('login', loginDoUsuario)

//ao abrir a pagina de login
//obter o localstorage
var admin = localStorage.getItem('admin')
var login = localStorage.getItem('login')
$.ajax({
  type: 'post',
  url: 'verify_login.php',
  data: ({admin,login})
  success: data=>{
    if(data=='aprovado'){
      //ir para dashboard
    }
  },
  error: erro=>{
   console.log(erro)
  }
})

In the backend ->

<?php
    //verifica se tinha um usuario logado e se ele é admin
    if (isset($_POST['login']) && isset($_POST['admin'])){
        if ($_POST['admin'] == '1'){ // se for admin deixa entrar sem refazer o login
            echo json_encode('aprovado');
        }else{
            echo json_encode('reprovado'); //se nao for lamento muito
        }
        die;
    }

    echo json_encode('reprovado'); //se ainda nao logou entao tem q logar
?>
  • db_connect only connects to the database. I left inside the script where this code is (hidden here so it doesn’t get so big in this topic). You think me putting it underneath might have interfered with the outcome?

  • What information does this db need to be able to see if the user is admin or not? the login coming from the correct _SESSION? something like if -> ! isset($_SESSION['login'])-> go to login page, lse -> check whether this login is admin or not.. Anyway I do not know how you are capturing this admin information..

  • I understand, as I am very lay in the subject yet, maybe I am having a noise in our communication because I do not know how to express properly. Basically, I have a DB that I made completely manual with: id (auto increment), username, password and admin. This admin status, I put for only two users. When they log into these accounts, they are directed to a special administrator area. I will add in the code of the post the bottom part, to see if the error could be in this.

Browser other questions tagged

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