PHP form token usage and handling

前端 未结 3 2066
日久生厌
日久生厌 2020-11-30 22:55

I\'m a beginner working on a login script in PHP. This is the form token statement that I have so far:

$_SESSION[\"form_token\"] = md5(rand(time (), true)) ;         


        
3条回答
  •  庸人自扰
    2020-11-30 23:44

    There is no need to do what you are attempting. When you start a session in PHP with session_start() a unique SESSIONID is already generated for you. You should not be putting this on the form. It is handled via cookies by default. There is also no need to check the SESSIONID either, that again is handled for you.

    You are responsible for authenticating the user and storing their authenticated identity (e.g. $_SESSION['user_id'] = $userId in the SESSION. If a user logs out you destroy their session with session_destroy.

    You should ensure session_start() is one of the first things for all pages in your site.

    Here is a basic example:

    login($username, $password)) {
            $_SESSION['user_id'] = $user->getId();
            return true;
        }
        return false;
    }
    
    function logout()
    {
        session_destroy();
    }
    
    function isLoggedIn()
    {
        return isset($_SESSION['user_id']);
    }
    
    function generateFormHash($salt)
    {
        $hash = md5(mt_rand(1,1000000) . $salt);
        $_SESSION['csrf_hash'] = $hash
        return $hash;
    }
    
    function isValidFormHash($hash)
    {
        return $_SESSION['csrf_hash'] === $hash;
    }
    

    Edit: I misunderstood the original question. I added the relevant methods above for generating and validating form hashes;

    Please see the following resources:

    • PHP Session Handling
    • session_start()
    • session_destroy()

提交回复
热议问题