PHP Directory-specific Content and Redirects
I have this code
$pageEx = explode("/", $_SERVER['PHP_SELF']);
$pageLn = count($pageEx);
$currentdir = $pageEx[$pageLn - 2];
switch($currentdir) {
case "admin":
if(!$this->loggedIn) {
header("Location: index.php");
}
if($this->userData['user_level'] < 3) {
header("Location: ../index.php");开发者_高级运维
}
break;
case "mgmt":
if(!$this->loggedIn) {
header("Location: index.php");
}
if($this->userData['user_level'] < 2) {
header("Location: ../index.php");
}
break;
case "user":
if(!$this->loggedIn) {
header("Location: index.php");
}
if($this->userData['user_level'] < 1) {
header("Location: ../index.php");
}
break;
}
and was just wondering whether there's a shorter way I could do it?
The code works, but its a lot of code for something so simple. It checks the directory they're in then if they aren't the right user_level it redirects them to the index page.Edit: Done it.
$pageEx = explode("/", $_SERVER['PHP_SELF']);
$pageLn = count($pageEx);
$currentdir = $pageEx[$pageLn - 2];
/*
User Level Required => Directory
*/
$permissions = array(
1 => 'user',
2 => 'mgmt',
3 => 'admin'
);
foreach($permissions as $perms => $key) {
if(!$this->loggedIn) {
header("Location: ../index.php");
}
if($currentdir == $key) {
if($perms > $this->userData['user_level']) {
header("Location: ../index.php");
}
}
}
How about this?
$pageEx = explode("/", $_SERVER['PHP_SELF']);
$pageLn = count($pageEx);
$currentdir = $pageEx[$pageLn - 2];
if(!$this->loggedIn) {
header("Location: index.php");
}
$permissions = array(
'admin' => 3,
'mgmt' => 2,
'user' => 1,
);
if($this->userData['user_level'] < $permissions[$currentdir]) {
header("Location: ../index.php");
}
UPDATE: I just noticed you wanted to do a LESS THAN... so I updated the code to reflect the way it works in your code.
You might cringe at this, but you could get it down to 6 lines if the long if statement doesn't bother you...
$pageEx = explode("/", $_SERVER['PHP_SELF']);
$currentdir = $pageEx[count($pageEx) - 2];
if(!$this->loggedIn)
header("Location: index.php");
elseif(($currentdir == "admin" && $this->userData['user_level'] < 3) || ($currentdir == "mgmt" && $this->userData['user_level'] < 2) || ($currentdir == "user" && $this->userData['user_level'] < 1))
header("Location: ../index.php");
Note the change to an elseif because--and correct me if I'm mistaken--either the user is not logged in and gets redirected to index.php or the user is logged in and might get directed to ../index.php. If they were separate if statements, it seems there could end up being two Location headers.
精彩评论