Hide login page for logged in users

Asked

Viewed 46 times

0

I made a code for when the user is logged in, can not access the login page, and can be redirected to the panel page. Both the admin’s and the user’s are working, but when someone logged in access the login page, these errors appear

Notice: Undefined index: nivel in C: Program Files (x86) Easyphp-Devserver-14.1VC9 data localweb site tcc login.php on line 5

Notice: Undefined index: nivel in C: Program Files (x86) Easyphp-Devserver-14.1VC9 data localweb site tcc login.php on line 9

And the code that I used to do this redirect was this

<?php
session_start();
include "php/conexao.php";

if($_SESSION['nivel'] == "admin"){ 

    header("Location:admin/index.php");

}elseif($_SESSION['nivel'] == "usuario"){

    header("Location:usuario/index.php");

}else{
    echo "loga ai po";
}
?>

1 answer

1


The error exists because for someone who is not logged in, the key nivel there is no. Unlike Javascript, which only returns undefined, PHP throws an error when trying to access a missing key.

Before checking what is in the key, check if it exists with isset($_SESSION['nivel']) or array_key_exists('nivel', $_SESSION), example:

if( !isset($_SESSION['nivel']) ) { 
    /*não está logado*/

} elseif( $_SESSION['nivel'] == 'admin' ) {
    /*administrador*/

} else {
    /*usuario*/
}
  • I switched the code I was using with this one and now it’s working 100%, thank you!

Browser other questions tagged

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