开发者

How to separate the application logic before and after log in?

Here is the idea.... ...I have a index.php.... ... The application is have one page开发者_JS百科 only, just like the facebook wall, if the user is logined, they can see their "wall", but if they are not logined, they see a register page.... ....

Should I put all these login in the index.php? or I need to separate two index.php...one is logined_index.php, and notLogined_index.php??

Moreover, how can I prevent someone who is not logined in the index.php? Thank you.


If your application will remain small there is no need for a separate file. You can use something like this:

<?php
    session_start();
    if (!isset($_SESSION['uid']) | $_SESSION['uid']=='') $_SESSION['uid']=0;

    if($_SESSION['uid']!=0) {
        if (/* user logs out */) {
            session_destroy();
            /* show register/login form */
        }
        else {
            /* main page code goes here */
        }
    }
    else {
        if (/* register details entered */) {
            if (/* register details valid */) {
                /* register the user and display it all went successful */
            }
            else {
                /* wrong register info - display error */
            }
        }
        else if (/* login details enetered */) {
                if (/* user exists and login correct */) {
                $_SESSION['uid'] = /* set the id of the logged user */;
                /* log user in and redirect to main page */
            }
                        else {
                /* wrong login info - display error */
            }
        }
        else {
            /* show register/login form */
        }
    }
?>

This is just a simple code layout to build on.


I suggest you put login page in a separate file and redirect there from every page that requires login, like this, for example:

<?php
// at the very beginning of index.php
if($not_logged_in){
    // redirect user to a login page
    header('Location: /login_please.php?return_to='.urlencode($_SERVER['REQUEST_URI']));
    die();
}
?>


You should understand what session for.

If it is one page app you could make your index.php to act as controller and can create separate template or views for login and register.

And check what user is requesting for if they are not allowed to access that page without log in check the session and redirect them to register or log in view. if they are already logged in redirect them to your wall or protected page.

for an example

session_start()
if(isset($_SESSION['user_id']))
{
  //user is logged in and redirect them to main page
}
else
{
  //ask him to register or log in
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜