2

I want to write a script that can only be accessed by an administrator.

This is how I want to do it:

session_start();

if (!isset($_SESSION['user_id'])) { //not logged in

    //redirect to homepage
    header("Location: http://domain.com/index.php");
    die();

}

if ($_SESSION['user_level'] != 1337) { //not admin

    //redirect to homepage
    header("Location: http://domain.com/index.php");
    die();

}

if ($_SERVER['REQUEST_METHOD'] == 'POST') { //form is submitted

    //validate the submitted data
    //submit the query

}

//form goes here

My question is: Is there a better way of validating this (eg. should all three conditionals be nested) or is this enough?

Cheers,

n1te

4
  • you can use IF ELSEIF ELSE it is more suitable for the situation. Commented Oct 30, 2012 at 12:00
  • It wouldnt really matter because you're die()ing anyway Commented Oct 30, 2012 at 12:00
  • Fair enough, but is there a better way of validating this? Commented Oct 30, 2012 at 12:02
  • 1
    Make them functions as pointed out. Commented Oct 30, 2012 at 12:06

3 Answers 3

4

If it's not possible that persons rights will change on the fly (namely: you remove admins right), then this should be enough, although I'd build a function:

function IsAdmin() {
    if( !isset($_SESSION['user_level'])){
        return false;
    }

    return ($_SESSION['user_level'] == 1337);
}

For the case you'll use extended rights checking in future.

Sign up to request clarification or add additional context in comments.

Comments

1

The following is a little tidier... though you may want to run some validation on $_SESSION['user_id'] to ensure that it is an int or whatever datatype you are expecting...

session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['user_level'] != 1337) { //not logged in

    //redirect to homepage
    header("Location: http://domain.com/index.php");
    exit(); // NOT DIE :P

}


if ($_SERVER['REQUEST_METHOD'] == 'POST') { //form is submitted

    //validate the submitted data
    //submit the query

}

//form goes here

1 Comment

use 'is_numeric' maybe to validate the $_SESSION['user_id'] after verifying that it existes, else you will get an unidentified index error
0

I'd write:

if (!isset($_SESSION['user_id']) || $_SESSION['user_level'] != 1337) {
    //not logged in/not admin
    //redirect to homepage
    header("Location: http://domain.com/index.php");
    die();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.