2012-11-26 45 views
0

我有一段代码,我只是写,检测是否有登录和用户,如果[1] [2]有串在任何特定的文本,然后将迁至该人向另一人页面是否符合值。简化PHP如果公司和数组

但我认为我的代码是一个小长篇大论。有什么方法可以简化我拥有的或者我会得到的最好的?

if (!isset($_SESSION['user_id'])){ 
    $dir = dirname($_SERVER['PHP_SELF']); 
    $dirs = explode('/', $dir); 
    if(isset($dirs[1])){ 
     if (($dirs[1] == "account") || ($dirs[1] == "admin")){ 
      header('Location: /'); 
     } 
    } 
    if(isset($dirs[2])){ 
     if(($dirs[2] == "account")){ 
      header('Location: /'); 
     } 
    } 
} 

在此先感谢

+1

也许你可以使用mod_rewrite并为这些路径指定重写规则? –

+0

已修改代码,该代码片段在if语句中以检查用户是否已登录 – ngplayground

回答

2

一个简单的方法是使用封闭

$dir = explode('/', dirname($_SERVER['PHP_SELF'])); 

$is = function($pos, $check) use($dir) { 
    return array_key_exists($pos, $dir) && $dir[$pos] == $check; 
}; 

if($is->__invoke(1, 'account') 
    || $is->__invoke(1, 'admin') 
    || $is->__invoke(2, 'account')) { 
    header('Location: /'); 
} 
1

你能做到这一点,例如:

$dir = dirname($_SERVER['PHP_SELF']); 
$dirs = explode('/', $dir); 

if(in_array('account',$dirs) || in_array('admin', $dirs)){ 
    header('Location: /'); 
} 
+1

,现在是Bgi&James的组合:'if(in_array(array('account','admin'),$ dirs) )header('Location:/');' –

+0

我用一个回声代替标题来测试页面响应。它什么都不返回。 – ngplayground

+0

的如果以检查$显示目录被正确创建 – Bgi

0

其中几个简单的解决方案可能是使用PHP的array_intersect($array1, $array2)函数。这是有据可查的php.net website,但这里有一个小例子:

// Define all the 'search' needles 
$needles = array('account', 'admin'); 

// Get all the dirs 
$dirs = explode('/', dirname($_SERVER['PHP_SELF'])); 

// Check for needles in the hay 
if(array_intersect($needles, $dirs)) 
{  
    // Redirect 
    header('Location: /');  
} 

新增:当然,你可以通过多条线路组合成一个作出上述非常简单,这将留给你:

if(array_intersect(array('account', 'admin'), explode('/', dirname($_SERVER['PHP_SELF'])))) 
{ 
    header('Location: /'); 
} 
+0

我用一个回声替换头来测试页面响应。它什么都不返回。 – ngplayground

+0

该网站的网址是什么?如果你的URL类似于site.com/index.php,它将只返回一个数组项:'/',但是如果URL是site.com/admin/index.php,你会得到两个:'/' &'admin' – James

+0

好的,我已经做了一些进一步的研究,并发现了另一个比较两个数组更可靠的PHP函数array_intersect()。我会更新我的帖子来改用它。 – James