使用ONE inc_文件中的会话的用户登录状态

时间:2012-02-02 03:48:47

标签: php mysql session

我正在尝试创建一个php include文件添加到我的所有页面,因此我可以隐藏未登录用户的某些页面信息。

我希望我已经对代码进行了充分的评论,以明确我的计划......

这是尝试将所有这些保存在一个文件中的最佳方式,而不是制作4或5个其他文件来处理用户的登录状态吗?

非常感谢所有输入。感谢。

php session_start(); 

// $layout is the top half of a div that will contain the login status bar (the closing tag is at the bottom of this include file.
$layout='
    <style type="text/css">
    body {
        font-family: Arial, Helvetica, sans-serif;      
        margin:0px;
    }
    .loginbar {
        font-size: 12px;
        text-align: right;
        padding-top: 5px;
        padding-right: 25px;
        height: 35px;
        width: 100%;
        color: #fff;
        background-color: #404040;
    }
    </style>
    <div class="loginbar">';

if ($_GET['logout']=='yes'){ // Has the user clicked the log out link?

    start_session();
    destroy_session();

} else { // No, so carry on..

        if !isset($_SESSION['lastname']){ //Is a session already running?

            if(!empty($_POST['user']) || !empty($_POST['pass'])) {
                #READ $_POST and check $_POST['username'] && $_POST['password'] against the database entries and get the respective 'FirstName' and 'LastName' of the user.
                # Set Session vars

                } else (empty($_POST['user']) || empty($_POST['pass'])) {
                echo $layout;
                # DISPLAY LOGIN FORM -> form will resend to this page
                }

        } else {
            echo $layout;
            echo "WELCOME ".$FirstName." ".$LastName;
            #display LOG OUT link. -> Link will send $_GET['logut='yes'] back to this page.
        }
}
?>
</div>

<?php /*
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//In any pages that this inc file is used, I will attempt to block certain bits of information like this:

<?php if ($_SESSION["lastname"]){ ?>
<p style="color:#ff0000;">This is some text that you should only be able to read if you have logged in.</p>
<?php } ?> 

//////////////////////////////////////////////////////////////////////////////////////////////////////////
*/
?>

1 个答案:

答案 0 :(得分:0)

基本上,您的工作流程还可以。 首先,我建议您在进一步使用之前确保验证所有用户输入。 其次,当设计需要改变时,将布局的一部分保留为变量可能会导致问题。为这样的事情组织模板文件会更好,并且将来会为您节省大量时间。

接下来,就像你在这里有代码一样,你似乎被迫将html转储到你的页面中。如果你只想检查登录状态,我认为你应该尝试清理你在这里输出的更多输出信息,将它们留在包含这个文件的php文件中。

因此,对于更复杂的东西,您将无法将登录逻辑完全分离为单个文件,并且无需权衡取舍。

我希望我理解你的问题,而且我不是偏离主题的。)