Pandjie Soerja Pandjie Soerja - 3 months ago 12
PHP Question

User-role based login always redirect to the same page

I want to redirect users to different page based on their role using PHP. But, the problem is, whoever the user, they'll always redirected to the same page (page where the first if-statement referred).

here's the code

<?php
include("config.php");
session_start();

if($_SERVER["REQUEST_METHOD"] == "POST") {

$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);

$sql = "SELECT * FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = isset($row['active']);
$count = mysqli_num_rows($result);

$role = isset($row['role']);

if($role == 'admin'){
$link = 'admin.php';
}
elseif($role == 'user'){
$link = 'user.php';
}
elseif($role == 'expert'){
$link = 'expert.php';
}
else{
$link = '404.php';
}

if($count == 1) {
$_SESSION['username'] = $myusername;

header("Location: ".$link."");
exit();
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>


So, if i replace admin.php on the first if statement with another page, the users will be redirected there. I've followed solutions from different case, but it didnt work.

Answer

This line

$role = isset($row['role']);

Sets $role to true or possibly false but it definitely does not set it to the contents of $row['role']

I would suggest removing that line completely it is not necessary as your if/elseif/else covers all the possible options quite nicely.

It is also totally unnecesary to move a value from the $row array into a scalar variable so this would be simpler

//$role = isset($row['role']);

if($row['role'] == 'admin'){
    $link = 'admin.php';
} elseif($row['role'] == 'user'){
    $link = 'user.php';
} elseif($row['role'] == 'expert'){
    $link = 'expert.php';
} else{
    $link = '404.php';
}

Unfortunately I have to mention that: Your script is at risk of SQL Injection Attack Have a look at what happened to Little Bobby Tables Even if you are escaping inputs, its not safe! Use prepared parameterized statements

It is also very dangerous storing plain text password on your database. The most likely attack vector on your database is internal staff. Therefore all passwords shoudl be HASHED. PHP provides password_hash() and password_verify() please use them.

Comments