简体   繁体   中英

How can I implement an access control system with session variables?

On the login page, I set a session variable with an ID (we are assuming that ID of 1 is always admin). When a user browses to the page that only an admin has access to, check.php acts as a middleman that checks to see if a session variable is set and if it is 1, then it will redirect the user to the admin page, and another page if it is not. Here is my code:

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

    #Check to see if session variables are set properly. Only the administrator can have access to this page
    if(!isset($_SESSION) || $_SESSION['id'] != 1) {
        header('Location: restricted.php');
        die();
    } else {
        header('Location: admin.php');
        die();
    }
 ?>

When I go to my login page and successfully login with admin credentials, and try the check.php page, it takes me to admin.php. If I don't log in it still takes me to the admin page.

What exactly is my issue with this script?

Because the else will execute if the conditions aren't met. Either change the redirect in the else or create another set of conditions.

 if(!isset($_SESSION) || $_SESSION['id'] != 1) { // CONDITION NOT MET
        header('Location: restricted.php');
        die();
    } else {
        header('Location: admin.php'); // REDIRECT OCCURS
        die();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM