Reputation: 945
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
Upvotes: 2
Views: 13549
Reputation: 20997
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.
Upvotes: 4
Reputation: 8616
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();
}
Upvotes: 0
Reputation: 5605
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
Upvotes: 1