How to redirect user after login according to user type?

Asked

Viewed 1,589 times

2

in the system there are 2 types of users 1 = admin and 2 = teacher, and after logging in need redirect each to a different page. This is my php and html code.

require "lib/authenticate.php";
$error = false;
$password = $email = $user_tipo = "";

if (!$login && $_SERVER["REQUEST_METHOD"] == "POST") {
 if (isset($_POST["email"]) && isset($_POST["password"])) {

    $conn = connect_db();

    $email = mysqli_real_escape_string($conn,$_POST["email"]);
    $password = mysqli_real_escape_string($conn,$_POST["password"]);
    $password = md5($password);

    $sql = "SELECT user_ID,name,email,password,tipo FROM users
        WHERE email = '$email';";

    $result = mysqli_query($conn, $sql);
    if($result){
        if (mysqli_num_rows($result) > 0) {
            $user = mysqli_fetch_assoc($result);

            if ($user["password"] == $password) {

                $_SESSION["user_id"] = $user["user_ID"];
                $_SESSION["user_name"] = $user["name"];
                $_SESSION["user_email"] = $user["email"];
                $_SESSION["user_tipo"] = $user["tipo"];

                header("Location: " . dirname($_SERVER['SCRIPT_NAME']) .     "/index.php");
                exit();
            }
            else {
                $error_msg = "Senha incorreta!";
                $error = true;
            }
        }
        else{
            $error_msg = "Usuário não encontrado!";
            $error = true;
        }
    }
    else {
        $error_msg = mysqli_error($conn);
        $error = true;
    }
}
else {
    $error_msg = "Por favor, preencha todos os dados.";
    $error = true;
}

}


?>
<!-- FIM PHP LOGIN -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>[WEB 1] Exemplo Sistema de Login - Registro</title>
<script src="js/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<!--Import Google Icon Font-->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

</head>
<body>

<!-- INICIO HTML LOGIN -->

<?php
 if ($user_tipo == 1): {
    header('Location: admin.php');
 } else ($user_tipo != 1): {
     header('Location: perfil.php')
 }

?>

</body>
</html>
<?php exit(); ?>
<?php endif; ?>



<?php if ($error): ?>
<h3 style="color:red;"><?php echo $error_msg; ?></h3>
<?php endif; ?>
<div class="container">
<div class="row">
    <div class="col-md-offset-5 col-md-3">
        <div class="row">

            <div class="col s4">

            </div>
            <form class="col s4" action="<?php $_SERVER['PHP_SELF'] ?>"   method="post">
                <h5>Evo System <br><small>faça o login</small></h5>
                <label for="email">Email: </label>
                <input type="text" name="email" class="form-control  input-sm chat-input" placeholder="[email protected]" value="<?php echo $email;   ?>" required><br>

                <label for="password">Senha: </label>
                <input type="password" name="password" value="" class="form-control input-sm chat-input" placeholder="sua senha"  required><br>


                <div class="wrapper">
                    <span class="group-btn">     
                        <input class="btn btn-primary btn-md center-block" type="submit" name="submit" value="Entrar">
                    </span>
                </div>
            </form>
            <div class="col s4"></div>
        </div>

    </div>
  </div>
</div>
<!-- FIM HTML LOGIN -->
</div>




  <!--Import jQuery before materialize.js-->
  <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script type="text/javascript" src="js/materialize.min.js"></script>
  <script type="text/javascript">
        $(document).ready(function() {
             Materialize.updateTextFields();
        });
  </scrip>

</body>
</html>

  • 1

    It wouldn’t be enough to make a if in $user["tipo"] and use header("Location") for the different pages?

  • So, that’s what I’m trying to do there, but if I put 2 if, or the Else there in the same, if I log in with admin it works, if logging in with the other does not pass, continue on the login screen.

  • Anderson, if you could be more specific, maybe I’d better understand what I’m doing wrong. I’m not experienced so I may be missing something by being a beginner.

  • After logging in, the user is not redirected to the page index.php? This is the page index.php?

  • This I’m doing this code on the index.php page

  • where this $login comes from?

Show 1 more comment

3 answers

0

You are issuing a header after sending the body, which is sent by <!-- FIM PHP LOGIN -->, this is not allowed, by default you should be getting a:

Warning: Cannot Modify header information - headers already sent by

If this "worked".


To fix can simply do:

//...

$redirecionamentos = [
    '1' => 'admin.php',
    '2' => 'perfil.php',
];

if (array_key_exists($_SESSION['user_tipo'], $redirecionamentos)) {

    header('Location: ' . $redirecionamentos[ $_SESSION['user_tipo'] ], true, 302);

}

?>
<!-- FIM PHP LOGIN -->
<!DOCTYPE html>
<html>
<head>

</head>
</html>
//...

Using this order, before HTML, this could work, just as you can use any of the solutions that were presented before. In this specific case, if the user is 1 or 2 it will redirect to the respective location, determined by the array. The header before the body, as expected. The header will have the location, defined by $redirecionamentos[ $_SESSION['user_tipo'] ], as well as the code, 302, temporary redirect.


Just because I can’t sit still, but it’s out of the question asked.

  1. Do not use MD5() it is considered broken:

    • Most passwords are weak and predictable, the Rockyou.txt is a very strong dictionary, uniting to the hashcat.
    • PHP has the password_hash() and the hash_pbkdf2() natively, with adjustable cost and suitable support for salt.
  2. Forget the $user["password"] == $password:

    • It is vulnerable by comparing with weak typing, try using md5('aabg7XSs') == md5('240610708') and tell me the result, because it is.
    • It is vulnerable by timming-Attack since it uses memcmp.

0


Your code is wrong, you can’t use a condition within a else and you didn’t use it either ; after the last parentheses of header no Adm user. Fix by:

<!-- INICIO HTML LOGIN -->

<?php
 if ($user_tipo == 1): {
    header('Location: admin.php');
 } elseif ($user_tipo != 1): {
     header('Location: perfil.php');
 }

?>

0

This redirect could have been done before, even because all code that works with headers (sessions, cookies, redirects and encryption) must be sent, created, defined and modified before HTML.

if ($user["password"] == $password) {

    $_SESSION["user_id"] = $user["user_ID"];
    $_SESSION["user_name"] = $user["name"];
    $_SESSION["user_email"] = $user["email"];
    $_SESSION["user_tipo"] = $user["tipo"];

    $_user_tipo=$user["tipo"];

    if ($_user_tipo == 1): {
        header('Location: admin.php');
        } elseif ($_user_tipo == 2): {
        header('Location: perfil.php')
        }else{
        //caso nenhum dos dois
    }
    exit();
}   

Browser other questions tagged

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