我有这段代码
$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;
}
并且只是想知道我能做的更短的方式吗? 代码可以工作,但它的代码非常简单 它会检查它们所在的目录,如果它们不是正确的user_level,则会将它们重定向到索引页面。
修改:完成。
$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");
}
}
}
答案 0 :(得分:3)
这个怎么样?
$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");
}
更新:我刚刚注意到你想做的不多......所以我更新了代码以反映代码的工作方式。
答案 1 :(得分:1)
你可能会对此感到畏缩,但如果long if语句不打扰你,你可以把它降到6行......
$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");
注意对elseif的更改,因为 - 如果我弄错了,请更正我 - 用户未登录并被重定向到index.php或用户已登录并可能被定向到../ index.php文件。如果它们是单独的if语句,那么最终可能会有两个Location头。