How to check if a user is logged-in in php?

后端 未结 9 1426
南方客
南方客 2020-12-02 05:21

I\'m pretty new to php and I am trying to figure out how to use sessions to check and see if a user is logged into a website so that they would have authorization to access

相关标签:
9条回答
  • 2020-12-02 05:52

    Need on all pages before you check for current sessions

    session_start();
    

    Check if $_SESSION["loggedIn"] (is not) true - If not, redirect them to login page.

        if($_SESSION["loggedIn"] != true){
           echo 'not logged in';
           header("Location: login.php");
           exit;
        }
    
    0 讨论(0)
  • 2020-12-02 05:53

    you may do a session and place it:

    //start session
    session_start(); 
    
    //check do the person logged in
    if($_SESSION['username']==NULL){
        //haven't log in
        echo "You haven't log in";
    }else{
        //Logged in
        echo "Successfully log in!";
    }
    

    note:you must make a form which contain $_SESSION['username'] = $login_input_username;

    0 讨论(0)
  • 2020-12-02 05:54

    Logins are not too complicated, but there are some specific pieces that almost all login processes need.

    First, make sure you enable the session variable on all pages that require knowledge of logged-in status by putting this at the beginning of those pages:

    session_start();
    

    Next, when the user submits their username and password via the login form, you will typically check their username and password by querying a database containing username and password information, such as MySQL. If the database returns a match, you can then set a session variable to contain that fact. You might also want to include other information:

    if (match_found_in_database()) {
        $_SESSION['loggedin'] = true;
        $_SESSION['username'] = $username; // $username coming from the form, such as $_POST['username']
                                           // something like this is optional, of course
    }
    

    Then, on the page that depends on logged-in status, put the following (don't forget the session_start()):

    if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
        echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
    } else {
        echo "Please log in first to see this page.";
    }
    

    Those are the basic components. If you need help with the SQL aspect, there are tutorials-a-plenty around the net.

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