Skip to content
Advertisement

How to make login system with access levels with users registered in different tables?

I would like to be told how do I create a php login system with access levels, but with users registered in different SQL tables. Some time ago, I made a login system also with access levels, but with users registered in a single table, ie, what set them apart was a field that I created in the table called “id_permissoes”.

This was the code you used:

<?php
// Initialize the session
session_start();

  // Verifica se não há a variável da sessão que identifica o usuário

  if ($_SESSION['nivelAcesso'] == 1) {
      // Redireciona o visitante de volta pro login
      header("Location: admin"); 
  }

  if ($_SESSION['nivelAcesso'] == 2) {
      // Redireciona o visitante de volta pro login
      header("Location: co"); 
  }

  if ($_SESSION['nivelAcesso'] == 3) {
      // Redireciona o visitante de volta pro login
      header("Location: cc"); 
  }

// Include config file
require_once "config.php";

// Inicializa variáveis
$email = $password = "";
$email_err = $password_err = "";

// Processing form data when form is submitted
if(isset($_REQUEST["submit"])){

    // Verifica e-mail vazio
    if(empty(trim($_REQUEST["email"]))){
        $email_err = "Introduza o seu email.";
    } else{
        $email = trim($_REQUEST["email"]); // trim -retira espaços no princípio ou fim da string
    }

    // Verifica password vazia
    if(empty(trim($_REQUEST["password"]))){
        $password_err = "Introduza a sua password.";
    } else{
        $password = trim($_REQUEST["password"]); // trim -retira espaços no princípio ou fim da string
    }

    // Valida credenciais
    if(empty($email_err) && empty($password_err)){
        // Prepara select statement
        $stmt = $pdo->prepare("SELECT id_admin, nome, apelido, email, password, id_permissoes, primeiro_acesso FROM administradores WHERE email = :email");

        if($stmt){
            // Faz o bind das variáveis com os parametros do statement
            $stmt->bindParam(":email", $param_email);

            // Set parameters
            $param_email = trim($_REQUEST["email"]);

            // Executa o statement
            if($stmt->execute()){
                // Verifica se o email existe na base de dados. Se sim, valida a password
                if($stmt->rowCount() == 1){
                    if($row = $stmt->fetch()){
                        $id = $row["id_admin"];
                        $email = $row["email"];
                        $nome = $row["nome"];
                        $apelido = $row["apelido"];
                        $permissoes = $row["id_permissoes"];
                        $primeiro_acesso = $row["primeiro_acesso"];

//                        $hashed_password = $row["password"];
                        if($password===$row["password"]){
//                        if(password_verify($password, $hashed_password)){

                            // Password correta, inicia sessão
                           if (!isset($_SESSION)) session_start();

                            // Guardar autenticação em variáveis de sessão
                            $_SESSION["id"] = $id;
                            $_SESSION["email"] = $email;
                            $_SESSION["nome"] = $nome;
                            $_SESSION["nivelAcesso"] = $permissoes;
                            $_SESSION["apelido"] = $apelido;
                            $_SESSION["primeiro_acesso"] = $primeiro_acesso;

                            // Redireccionar para a página de acolhimento

                            if(isset($_SESSION['destino']) && $_SESSION['destino'] != "") {
                                header("Location: ".$_SESSION['destino']);

                            }else{
                                if($_SESSION["nivelAcesso"] == "1"){
                                header("Location: admin");

                            }elseif($_SESSION["nivelAcesso"] == "2"){
                                header("Location: co");

                            }else{
                                header("Location: cc");

                            }
                            }


                        } else{
                            // Mensagem de erro, caso password errada
                            $password_err = "A password que introduziu não é válida.";
                        }
                    }
                } else{
                    // Mensagem de erro, caso user não exista
                    $email_err = "Email não existente.";
                }
            } else{
                echo "Oops! Alguma coisa correu mal aqui.";
            }
        }

        // Close statement
        unset($stmt);
    }

    // Close connection
    unset($pdo);
}
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>CC | BackOffice</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Font Awesome -->
  <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
  <!-- icheck bootstrap -->
  <link rel="stylesheet" href="plugins/icheck-bootstrap/icheck-bootstrap.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="dist/css/adminlte.min.css">
  <!-- Google Font: Source Sans Pro -->
  <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
</head>
<body class="hold-transition login-page">
<div class="login-box">
  <div class="login-logo">
    <a href="#"><b>CC</b>BackOffice</a>
  </div>
  <!-- /.login-logo -->
  <div class="card">
    <div class="card-body login-card-body">
      <p class="login-box-msg">Digite os seus dados para iniciar sessão</p>

      <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                                <div class="form-group" <?php echo (!empty($email_err)) ? 'has-error' : ''; ?>">
                                    <label>email</label>
                                    <input class="au-input au-input--full" type="text" name="email" placeholder="email" value="<?php echo $email; ?>" autofocus>
                                    <span style="color:red;" class="help-block"><?php echo $email_err; ?></span>
                                </div>
                                <div class="form-group" <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
                                    <label>Password</label>
                                    <input class="au-input au-input--full" type="password" name="password" placeholder="Password">
                                    <span style="color:red;" class="help-block"><?php echo $password_err; ?></span>
                                </div>
                                <div class="login-checkbox">
                                    <label align="right">
                                        <a href="https://m.me/filipengine">Problemas no acesso?</a>
                                    </label>
                                </div>
                                <button class="au-btn au-btn--block au-btn--green m-b-20" type="submit" name="submit">Entrar</button>
                            </form>
    </div>
    <!-- /.login-card-body -->
  </div>
</div>
<!-- /.login-box -->

<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>

</body>
</html>

However, now the need has arisen to create 3 different tables to separate user types.

How do I do this validation?

I tried to test some if’s (if it doesn’t exist in one table, fetch in the other), but couldn’t.

Can you help me?

Thank you!

Advertisement

Answer

I am not sure 100% what you asking, What I understand is you are asking for redirection users to their role page.

I use to try that in a project with switch statements

  • Create a column call Role in your user table then add roles like :
  • role = 1 is admin
  • role = 2 is employees
  • role = 3 is normal user
  • role = 0 is unverified

Than redirect user where you get success and set sessions variables like this.

$_SESSION['role'] = $role; 
$role = intval($row['role']);
switch ($role){
case 0:
header("location: ../user/?log=activation");
break;
case 1: 
header("location: ../admin/index.php");
break;
case 2:
header("location: ../Upanel/");
break;
case 3:
header("location: ../Upanel/");
break;
} 

Hope this will give you an idea.

I realy dont understand what means login in 2 table 🙂

EDIT: Redirection users to login on their types :

Login with 3 tables add a simple condition like following into your login.php

    $(function(){
      // bind change event to select
      $('#dynamic_select').on('change', function () {
          var url = $(this).val(); // get selected value
          if (url) { // require a URL
              window.location = url; // redirect
          }
          return false;
      });
    });
<select id="dynamic_select">
  <option value="" selected>Please select login type</option>
  <option value="teacherLogin.php">Teacher</option>
  <option value="studentLogin.php">Student</option>
  <option value="adminLogin.php">Admin</option>
</select>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement