2

I use the below code on all my pages after initialising the SESSION data and defining the variable $auth_level.

I use this to decide what to show users of varying levels.

<?php
    if($auth_level == 'basic'){
        // auth_level basic
        if (!isset($_SESSION['username'])) {
            header('Location: login.php');
        }
    } else if ($auth_level == 'admin'){
        // auth level admin
        if (!isset($_SESSION['username']) || $_SESSION['role'] != 2) {
            header('Location: login.php');
        }
    } else {
        // auth level admin assumed for security
        if (!isset($_SESSION['username']) || $_SESSION['role'] != 2) {
            header('Location: login.php');
        }
    }
?>
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
Somk
  • 11,869
  • 32
  • 97
  • 143
  • 2
    If you don't put an `exit;` after `header('Location: ...);` the script won't stop at that point. Btw this is offtopic because http://codereview.stackexchange.com/ – Daniel W. Apr 07 '14 at 11:17
  • I may not have had enough coffee yet... but it looks like your checking auth level, then checking to see if the username is set in the auth_level=='basic' block. Should you check username first? – Brad Faircloth Apr 07 '14 at 11:18
  • Why say "if `$auth_level` is "admin" then do this, but if it's anything else then do the exact same? Why not simply do `if (basic) { } else { }`? – h2ooooooo Apr 07 '14 at 11:18
  • you can do one thing. You can make one file "navigator" and include it to each page. or else you can use any framework of php. – Techno Cracker Apr 07 '14 at 11:19
  • Sometime I have more than two user levels is why I have the extra statement. – Somk Apr 07 '14 at 11:19
  • This file is included into all of my files by default. I include the database connection file which in turn includes this as I want to make sure any pages accessing the database are user managed – Somk Apr 07 '14 at 11:20
  • @brad a good point but some files I define auth_level as none which means this file is not included from the db file. – Somk Apr 07 '14 at 11:23
  • @Max figured there was more to it... to me this looks good. I don't see any security reason why this would not work. – Brad Faircloth Apr 07 '14 at 11:33

1 Answers1

1

This one might help:

https://stackoverflow.com/a/1225668/1437605

shortly speaking: you should store some more information in $_SESSION to distinguish clients(like ip etc.) as otherwise, I could obtain your cookie with your sessionId and that could authenticate properly depending on how you get the 'username' and 'role' values.

Community
  • 1
  • 1
Bartłomiej Wach
  • 1,968
  • 1
  • 11
  • 17