如何正确处理重定向和包含页面?

时间:2013-04-17 12:00:57

标签: php authentication redirect include

我正在撰写一个小项目,一个页面,非注册用户只能访问少数几个页面,其他几个页面注册的页面,以及其他一些注册的页面。这是一个游戏,所以只有这些玩“匹配”才能访问后者。此外,我们会有一些页面,管理员(秘密页面)。这是结构:

$Public_Path = '/public_html/public/';
$Private_Path = '/public_html/private/';
$Secret_Path = '/public_html/secret/';

我通过/public_html/index.php传递所有内容并从那里包含文件。我认为最好将所有包含和重定向放在一个地方,而不是在每个文件的开头散布。问题是,代码在这里开始变得混乱,还有更多选项需要添加。是否有简化它的架构?这就是我的代码现在的样子:

// Some extra code goes here

// If an unregistered user tries to go anywhere he shouldn't
if (!file_exists($Public_Path . $Url . '/index.php') && empty($User))
  header ('Location: /login/');

// PUBLIC. Load the public pages
if (file_exists($Public_Path . $Url . '/index.php'))
  include $Public_Path . $Url . '/index.php';

// SECRET. Only for admin
else if (file_exists($Secret_Path . $Url . '/index.php') && in_array($User->email, $Admins))
  include $Secret_Path . $Url . '/index.php';

// PRIVATE. Load the template and include private pages
else if (file_exists($Private_Path . $Url . '/index.php'))
  {
  if ($UrlArray[0] != 'games' && $User->game == 0)
    header ('Location: /games/');

  if ($UrlArray[1] == 'save')
    include $Private_Path . $Url . '/index.php';
  else
    {
    $Page = $Private_Path . $Url . '/index.php';
    include $Include_Path . 'template.php';
    }
  }

// 404. Nor public nor private nor secret
else
  header ('Location: /error/404');

注意:我知道只能通过此访问index.php的限制,我自己强加了。

我的问题是,如何以某种方式订购此代码,这样我可以添加更多功能但只增加一点复杂性?如何减少后者?

1 个答案:

答案 0 :(得分:1)

我会考虑几个选项:

添加会话变量(例如,$_SESSION['userPath']),当用户登录时,将其带到授权路径:

$path = (isset($_SESSION['userPath']))?$_SESSION['userPath']:FALSE;

if($path){
  include $path . $Url . '/index.php';
} else {
  header ('Location: /login/');
}

您的格式适用于扩展,但如果将其更改为switch语句,则在语义上可能更容易阅读。这将要求您将其归结为上面提到的一个变量(例如$_SESSION['userPath'])变量。

switch ($path){
  case "Public_Path":
    header ('Location: /login/');
    break;
  case "Private_Path":
     if ($UrlArray[0] != 'games' && $User->game == 0){
      header ('Location: /games/');
     }
     if ($UrlArray[1] == 'save'){
      include $Private_Path . $Url . '/index.php';
     } else {
      $Page = $Private_Path . $Url . '/index.php';
      include $Include_Path . 'template.php';
     }
    break;
  case "Secret_Path":
    if (in_array($User->email, $Admins){
      include $path . $Url . '/index.php';
    }
    break;
  case "New_Path":
    include $path . $Url . '/index.php';
    break;

   // ...

  case default:
    header ('Location: /error/404');
}

最后,如果您使用AJAX解决方案,而不是重定向,页面将重新加载到查看器的适当位置。在这种情况下,根本不需要重定向,而只需在需要时加载所需的元素。