How to handle roles when starting session in php and mysql?

0

Hello good afternoon, I am trying to redirect the user to log on to the roll to which it is associated within the table, in this case there are two types, the admin roll and the limited roll. I want to know how this could be achieved. So far it is the following :, which basically is just the login without condition of roles.

    <?php session_start();

if (isset($_SESSION['usuario'])){

    header('Location: index.php');

}


if($_SERVER['REQUEST_METHOD']=='POST'){
    $usuario = filter_var(strtolower($_POST['usuario']),FILTER_SANITIZE_STRING);
    $password = $_POST['password'];
    $password = hash('sha512', $password);
    $errores ='';   
    try{
        $conexion = new PDO('mysql:host=localhost;dbname=centromedico','root','');
    }catch(PDOException $e){
        echo "Error: ". $e->getMessage();
    }
    $statement = $conexion -> prepare(
            'SELECT * FROM usuarios');

    $statement ->execute(array(':usuario'=> $usuario,':password'=> $password ));

    $resultado = $statement->fetch();
    if($resultado !==false){
        $_SESSION['usuario'] = $usuario;
        header('Location: index.php');
    }else{
        $errores .= 'Datos incorrectos y/o invalidos!';
    }
}
    require 'vista/login.php';
?>


Y este es el index.php donde se redirige al menu.

    <?php session_start();
if (isset($_SESSION['usuario'])){
    header('Location: CenterMedicine.php');
}else{
    header('Location: login.php');
}   
?>
    
asked by Pablo 16.06.2018 в 20:16
source

1 answer

1

A switch case would give you the possibility of a default location and add others according to the role

<?php 

   session_start();
   $location = 'Location: login.php';

   if (isset($_SESSION['usuario'])){
      switch ($_SESSION['usuario']['rol']) {
        case 'admin':
           $location = 'Location: indexAdmin.php';
           break;
        case 'usuario':
           $location = 'Location: indexUsuario.php';
           break;
        case 'dotor':
           $location = 'Location: indexMedico.php';
           break;
        default:
           $location = 'Location: indexGenerico.php';
       }
   }

   header($location);
?>
    
answered by 16.06.2018 в 20:55