Securely creating and destroying login sessions in PHP

后端 未结 5 982
别跟我提以往
别跟我提以往 2020-12-13 00:58

This is my code to control authentication on a website. I\'m not sure if my logic is correct. If the username and password are correct the following happen:

         


        
5条回答
  •  悲哀的现实
    2020-12-13 01:35

    To securely destroy a session I would use the following code:

    session_start();
    // Unset all session values
    $_SESSION = array();
    // get session parameters 
    $params = session_get_cookie_params();
    // Delete the actual cookie.
    setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
    // Destroy session
    session_destroy();
    

    In order to destroy a session you need to start it first, as you have found out it doesn't work if you don't include session_start();

    The session_regenerate_id(); Function generates a new session id for the user. If used with true (session_regenerate_id(true);) then the old session id is deleted from the server when it generates a new one. The reason behind generating a new session id on every page is that it makes session hijacking much harder (Nearly Impossible?) to perform because of the users constantly changing session id.

    (View PHP.net manual on session_regenerate_id();)

    When authenticating a user you should always check something like the IP address or Browser, these are constant things sent in the request to the server that do not change in the life time of your session, and if they do then you know something dodgy it happening. I always create two session variable one that stores the user ID so I can query a database for data, and another that stores the users password, IP address and Browser String all in one hash (sha512).

    $user_id = $_SESSION['user_id'];
    $login_string = $_SESSION['login_string'];
    
    // Query Database and get hashed password
    
    $login_check = hash('sha512', $password.$ip_address.$user_browser);
    
    if($login_check == $login_string) {
         // Logged In!!!!
         return true;
    } else {
         // Not logged in
         return false;
    }
    

    The password is secure even though it is being stored in the session. This is because the password is hashed (Twice in this case) and because the session data is not stored on the users computer (Like cookies), it is stored in a session file.

    I wrote an article on wikihow.com about secure login and authentication, is can be found here.

提交回复
热议问题