php sessions to authenticate user on login form

前端 未结 7 1734
借酒劲吻你
借酒劲吻你 2020-12-01 07:29

I have the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.

7条回答
  •  囚心锁ツ
    2020-12-01 07:50

    what about using this to setup session

    session_start();
    if( isset($_POST['username']) && isset($_POST['password']) )
    {
        if( auth($_POST['username'], $_POST['password']) )
        {
            // auth okay, setup session
            $_SESSION['user'] = $_POST['username'];
            // redirect to required page
            header( "Location: index.php" );
         } else {
            // didn't auth go back to loginform
            header( "Location: loginform.html" );
         }
     } else {
         // username and password not given so go back to login
         header( "Location: loginform.html" );
     }
    

    and at the top of each "secure" page use this code:

    session_start();
    session_regenerate_id();
    if(!isset($_SESSION['user']))      // if there is no valid session
    {
        header("Location: loginform.html");
    }
    

    this keeps a very small amount of code at the top of each page instead of running the full auth at the top of every page. To logout of the session:

    session_start();
    unset($_SESSION['user']);
    session_destroy();
    header("Location: loginform.html");
    

提交回复
热议问题