Home > Blockchain >  Give access to pages to specific user types PHP
Give access to pages to specific user types PHP

Time:12-20

In my application I have 2 user types, admin and manager. I want the manager to have access to the dashboard.php only. For this in my users table I've set usertype as column and while signing up they have to mention what type of user they are. Based on this, after logging in the manager dashboard, I have a button that goes to dashboard.php. And in dashboard.php I'm checking the $_SESSION['usertype'] == 'manager'). If it is it'll allow the user to access that page otherwise it'll take him to login page. But it isn't working. Every time it is taking me to the login page and anyone can access the dashboard.php by putting in the URL.

manager.php

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

// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}

echo $_SESSION["usertype"];
?>
 
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
        body{ font: 14px sans-serif; text-align: center; }
    </style>
</head>
<body>
    <h1 >Welcome, <b><?php echo htmlspecialchars($_SESSION["usertype"]); ?></b>. All System Operational!</h1>
    <p>
        <a href='dashboard.php' >Inventory Management</a>
        <a href="reset-password.php" >Reset Your Password</a>
        <a href="logout.php" >Sign Out of Your Account</a>
    </p>
</body>
</html>

Dashboard.php

<?php

if ((isset($_SESSION["loggedin"]) && $_SESSION['usertype'] == 'manager')) {
   header('Location: '.$_SERVER['PHP_SELF']);
} else {
    header('Location: login.php');
}

?>
...

Login.php

<?php
// Initialize the session
session_start();
 
// Check if the user is already logged in, if yes then redirect him to welcome page
/* what happens if users are different?
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    header("location: welcome.php");
    exit;
}
*/
 
// Include config file
require_once "config.php";
 
// Define variables and initialize with empty values
$usertype = $password = "";
$usertype_err = $password_err = $login_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    // Check if usertype is empty
    if(empty(trim($_POST["usertype"]))){
        $usertype_err = "Please enter usertype.";
    } else{
        $usertype = trim($_POST["usertype"]);
    }
    
    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }
    
    // Validate credentials
    if(empty($usertype_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT id, usertype, password FROM users WHERE usertype = ?";
        
        if($stmt = $mysqli->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("s", $param_usertype);
            
            // Set parameters
            $param_usertype = $usertype;
            
            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Store result
                $stmt->store_result();
                
                // Check if usertype exists, if yes then verify password
                if($stmt->num_rows == 1){                    
                    // Bind result variables
                    $stmt->bind_result($id, $usertype, $hashed_password);
                    if($stmt->fetch()){
                        if(password_verify($password, $hashed_password)){
                            // Password is correct, so start a new session
                            session_start();
                            
                            // Store data in session variables
                            $_SESSION["loggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["usertype"] = $usertype;                            
                            
                            if($usertype == "admin"){
                                header("location: welcome_admin.php");
                            } elseif($usertype == "manager"){
                                header("location: welcome_manager.php");
                            }elseif($usertype == "delivery"){
                                header("location: welcome_delivery.php");
                            }
                        } else{
                            // Password is not valid, display a generic error message
                            $login_err = "Invalid usertype or password.";
                        }
                    }
                } else{
                    // usertype doesn't exist, display a generic error message
                    $login_err = "Invalid usertype or password.";
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            $stmt->close();
        }
    }
    
    // Close connection
    $mysqli->close();
}
?>
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <style>
        body{ font: 14px sans-serif; }
        .wrapper{ width: 360px; padding: 20px; }
    </style>
</head>
<body>
    <div >
        <h2>Login</h2>
        <p>Please fill in your credentials to login.</p>

        <?php 
        if(!empty($login_err)){
            echo '<div >' . $login_err . '</div>';
        }        
        ?>

        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div >
                <label>User Type</label>
                <input type="text" name="usertype"  value="<?php echo $usertype; ?>">
                <span ><?php echo $usertype_err; ?></span>
            </div>    
            <div >
                <label>Password</label>
                <input type="password" name="password" >
                <span ><?php echo $password_err; ?></span>
            </div>
            <div >
                <input type="submit"  value="Login">
            </div>
        </form>
    </div>
</body>
</html>

So how do I make this dashboard.php accessible to specified user type only?

CodePudding user response:

<?php
session_start();

if((isset($_SESSION["loggedin"]) && $_SESSION['usertype'] == 'manager')){
   header('Location: '.$_SERVER['PHP_SELF']);
}else {
    header('Location: login.php');
}

?>

use session start to resume the session you build.

Every page that will use the session information on the website must be identified by the session_start() function. This initiates a session on each PHP page. The session_start function must be the first thing sent to the browser or it won't work properly. It must precede any HTML tags.

https://www.php.net/manual/en/function.session-start.php

CodePudding user response:

I got it working by removing the (isset($_SESSION["loggedin"]) checking in dashboard.php. Now I'm only checking if the user is manager or not. so it goes like this

<?php
session_start();

if($_SESSION['usertype'] !== "manager"){
    header("location: login.php");
    exit;
}

?>

I guess logged in state doesn't need to be checked as it is getting already checked in the manager page.

  •  Tags:  
  • php
  • Related