如何将登录用户的内容仅包含在源代码中?

时间:2013-01-22 21:42:32

标签: php html security

确认用户已登录后,如何才能显示仅允许成员显示的页面?

例如

<?php
    start_session();
    if(isset($_SESSION[userLoggedIn]))
        echo 'welcome to the members area!';
    else
        echo 'You must log in first';
?>

OR

<?php
    start_session();
    if(!isset($_SESSION[userLoggedIn]))
        goto notLoggedIn;
?>
    welcome to the members area!
<?php
    notLoggedIn:
        echo 'You must log in first';
?>

OR

<?php
    start_session();
    if(isset($_SESSION[userLoggedIn]))
        include members.html;
    else
        include public.html
?>

我不喜欢在PHP中包含太多HTML。

使用include / require解决方案时,如何制作,以便人们不能直接访问html文件?例如include members.html;什么阻止用户输入网址~/members.html? ATM我正在使用WAMP,但我猜测服务器上有设置?

编辑:确定这就是我的计划:创建两个目录publicprivate并制作webroot public。我将有一个页面检查用户是否已登录,如果是这样,$ _GET ['destination']的值将用于包含private目录中的正确页面。我没有想过任何陷阱?

3 个答案:

答案 0 :(得分:2)

我建议反对goto,在这种情况下真的没有必要。如果你有多个页面并且不想混合HTML和PHP,那么使用includes是一个很好的方法。

如果您希望所有内容都包含在一个页面上,您可以设置一个变量:

<?php
    start_session();
    $logged_in = ($_SESSION['isLoggedIn'] == true);
    // Whatever else you need...
?>

然后,在页面的后面(可能在结尾处),使用alternative syntax,你可以这样做:

<?php if( $logged_in): ?>
    <p>Welcome to the member's area!</p>
<?php else: ?>
    <p>You must log in first!</p>
<?php endif; ?>

答案 1 :(得分:2)

  

我不喜欢在PHP中包含太多HTML。

好。然后将HTML移动到处理表示逻辑的HTML模板中:

 start_session();
 if(isset($_SESSION['userLoggedIn'])){
    require 'public_html/logged_in.php';

 }else{
    require 'public_html/public_area.php';
 }

更好的是,创建一个加载这些模板的函数,例如:

function load_template($file, array $vars){
  extract($vars);
  unset($file, $vars);
  require func_get_arg(0);
}
  

使用include / require解决方案时,如何让人们这样做   不能直接访问html文件吗?

有几种方法:

  • 在主脚本中定义一个常量;检查模板中是否定义了此常量,如果不是
  • 则退出
  • 或将变量传递给执行相同操作的模板
  • 或将这些模板放在网络根目录之外
  • 或使用.htaccess规则保护它们

我假设这些模板也是PHP脚本。但是当然你也可以在PHP之上使用某种模板系统,或创建你自己的...

答案 2 :(得分:2)

如果访问者未登录,请将访问者重定向,以保持PHP文件的清洁:

if (empty($_SESSION['user_id'])
{
    header('Location: /not_logged_in_page'); // Redirect to another page!
    exit;
}

// Continue with the loggedin user page...