How do I protect a page only for logged users?

前端 未结 4 1283
南旧
南旧 2020-12-11 02:59

I created a login form that works great. But I realized the page my user is directed to can still be accessed by anybody. How do I protect the page being accessed only vie

相关标签:
4条回答
  • 2020-12-11 03:15

    On the page that requires the user to be logged in check to see if they have a valid session. If not send them to the login page.

    if (!$_SESSION['myusername'])  
    {  
        header('location: /login.php');  
        exit;  
    }
    
    0 讨论(0)
  • 2020-12-11 03:17

    In each page/content with restricted access, you should authenticate the client/user. If people were crazy then you'd have to make the user fill in his details (username/password) in every page, but thanks to "HTTP cookies" - we don't have to do that.

    0 讨论(0)
  • 2020-12-11 03:31

    Every of your page should start with

    session_start();
    

    and you should not be using session_register( "variablename" ) as of PHP version 4.2, use

    $_SESSION["variable"] = value;
    

    so example page with is-logged-it checking would be:

    <?php
    session_start();
    if($_SESSION["loggedIn"] != true) {
        echo("Access denied!");
        exit();
    }
    echo("Enter my lord!");
    ?>
    

    and logging-in script:

    <?php
        /*
            ... db stuff ...
        */
    
    if( isset($user_info['url']) ) {
        $_SESSION["loggedIn"] = true;
        $_SESSION["username"] = $myusername;
        header('Location: ' . $user_info['url']); //Redirects to the supplied url from the DB
    } else {
        header("Location: error.htm");
    }
    ?>
    
    0 讨论(0)
  • 2020-12-11 03:39

    You should basically use session management to track whether a user is in an authenticated session or not. If not, you (re)direct them to the index page; if yes, you grant them access to whichever resource they requested.

    To use sessions, put your session setup functions at the top of every PHP script inside your application (setup functions include session handler, cookie domain and cookie name), and say session_start(). Then, check if a login flag has been defined in the current session like $_SESSION["user_is_logged_in"]. In the authentication page, you would of course define $_SESSION["user_is_logged_in"] = true; at some stage.

    0 讨论(0)
提交回复
热议问题