mysql将用户重定向到基于角色php的不同页面

mysql将用户重定向到基于角色php的不同页面

问题描述:

I need to redirect users to different pages based on the roles given to them in the database. Only the username and password is submitted on the login page. I have to fetch the role from the database which looks like this:

username  |  password  |  role
admin1       admin1       admin
alex12       alex12       (nothing to normal users)

Here is the code:

<?php 
    session_start();
    // conectare la baza de date
    $db = mysqli_connect("localhost", "root", "", "inregistrare");
    if (isset($_POST['login_btn'])) {
        $username = mysqli_real_escape_string($db,$_POST['username']);
        $password = mysqli_real_escape_string($db,$_POST['password']);
        $password = md5($password); // parola cryptata
        $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
        $result = mysqli_query($db, $sql);
        if (mysqli_num_rows($result) == 1) {
            $_SESSION['message'] = "Te poti Conecta!";
            $_SESSION['username'] = $username;
            header("location: clasa.php"); //spre o pagina
            
        }else{
            $_SESSION['message'] = "Parola gresita!";
        }
    }
?>


<head>
    <title>Conectare</title>
    <link rel="stylesheet" type="text/css" href="./css/index-style.css">
</head>
<body>
<?php
    if (isset($_SESSION['message'])) {
        echo "<div id='error_msg'>".$_SESSION['message']."</div>";
        unset($_SESSION['message']);
    }
?>


<form method="post" action="clasa.php"> <!-- modifica si aici cand modifici mai sus la php-->
    <table align="center">
        
        <tr>
            <th id="titlu" class="titlu" colspan="2">Conectare</th>
        </tr>
        <tr>
            <td class="border">Username:</td>
            <td class="border"><input type="text" name="username" class="text-input" size="20"></td>
        </tr>

        <tr>
            <td class="border">Password:</td>
            <td class="border"><input type="password" name="password" class="text-input" size="20"></td>
        </tr>
        <tr>
            <td class="spatiu"></td>
            <td class="spatiu"></td>
        </tr>
        <tr>
            <td><button class="register" type="submit" formaction="./register.php">Inregistrare</button></td>
            <td><button class="connect" type="submit" name="login_btn">Conectare</button></td>
        </tr>
    </table>
</form>
</body>
</html>

</div>

You should check the user role. Here is an example how you can check it.

P.S the adminfile.php and anotherfile.php is where you should redirect the user and can be whatever you want.

if (mysqli_num_rows($result) == 1) {
        $_SESSION['message'] = "Te poti Conecta!";
        $_SESSION['username'] = $username;
        $user = mysql_fetch_assoc($result);


        if($user['role'] == 'admin'){
            header("location: adminfile.php");
        }else{
            header("location: anotherfile.php");
        }


    }else{
        $_SESSION['message'] = "Parola gresita!";
    }

Use mysqli_fetch_row

$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_row($result)) {
    printf ("%s (%s)
", $row[0], $row[1]);
}

I can see that you've already got the answer from @leli.1337 But I thought I should give you same example in more secured way than the one you have above, bellow I'm using PDO prepared statements to prevent sql injections, and also There's no need to store success message /error message on a session variable.

Bellow is my code.

<?php
session_start();
// conectare la baza de date
$host_name = "localhost";
$u_name    = "root";
$u_pass    = "";
try {
        $db = new PDO("mysql:host=$host_name;dbname=inregistrare", $u_name, $u_pass);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $ex) {
        error_log($ex);

}
$loginMessage = ""; //will fill this at a later stage.

if (isset($_POST['login_btn'])) {

        $username = UserInput($_POST['username']);
        $password = UserInput($_POST['password']);

        try {


                $stmt = $db->prepare("SELECT username,password, role FROM users where username = ? ");
                $stmt->bindValue(1, $username);
                $stmt->execute();

                $result = $stmt->fetchall(PDO::FETCH_ASSOC);
                if (count($result) > 1) { // username corerct 

                        foreach ($result as $row) { // now lets validate password
                                if (password_verify($password, $row['password'])) {
                                        $loginMessage         = "<p style=\"color:green;\">Te poti Conecta!</p>"; //We don't really  need to store the success on a session.
                                        $_SESSION['username'] = $row['username'];

                                        if ($row['role'] === "admin") {
                                                //admin user
                                                header("location:admin.php");
                                        } elseif ($row['role'] === "") {
                                                header("location: clasa.php"); //spre o pagina
                                        }

                                } else {
                                        // password incorrect
                                        $loginMessage = "<p style=\"color:#f00\">Parola gresita!</p>";

                                }
                        }


                }

        }
        catch (PDOException $e) {

                error_log($e);
        }


}
function UserInput($data)
{

        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
}
?>
<head>
    <title>Conectare</title>
    <link rel="stylesheet" type="text/css" href="./css/index-style.css">
</head>
<body>
<?php
    echo $loginMessage;
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <table align="center">

        <tr>
            <th id="titlu" class="titlu" colspan="2">Conectare</th>
        </tr>
        <tr>
            <td class="border">Username:</td>
            <td class="border"><input type="text" name="username" class="text-input" size="20"></td>
        </tr>

        <tr>
            <td class="border">Password:</td>
            <td class="border"><input type="password" name="password" class="text-input" size="20"></td>
        </tr>
        <tr>
            <td class="spatiu"></td>
            <td class="spatiu"></td>
        </tr>
        <tr>
            <td><button class="register" type="submit" formaction="./register.php">Inregistrare</button></td>
            <td><button class="connect" type="submit" name="login_btn">Conectare</button></td>
        </tr>
    </table>
</form>
</body>
</html>

As you can see I'm using password_verify() to verify the password hash instead of the md5 you used so, on your register.php page you will need to hash the password like this:

$password = $_POST['password'];
// Now lets hash the password
$hash = password_hash($password, PASSWORD_DEFAULT);

instead of: $password= md5($_POST['password'];

So in your database you will store the $hash value

Thanks, Hope you find this more useful.