How do i make a token expire time

前端 未结 1 420
旧时难觅i
旧时难觅i 2021-01-27 03:32

I currently have functions to generate a token, but how would i go about making it expire?Also, what would be a good shelf-life for the token?

Token Generation code:

1条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 04:37

    Best practice is to have a database table that stores the information of tokens created...

    id | expiry_timestamp | token ...
    

    Then edit the code to store each token created with its expiry_timestamp...

    function token($length = 40, $expiry) {
        // Set expiry_timestamp..
        $expiry_timestamp = time() + $expiry;
    
        // Generate the token...
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $token = 12000;
        $token = srand(floor(time() / $token));
        for ($i = 0; $i < $length; $i++) {
            $token .= $characters[rand(0, $charactersLength - 1)];
        }
    
        /** Do a quick manipulation in the token table...
        * ...Connect to database table then execute following SQL statement..
        * mysqli_query($link, "INSERT INTO token_table (token, expiry_timestamp) VALUES($token, $expiry_timestamp)");
        */
    
        return array($token,$expiry);
    }
    

    Just incase you want to check if it has expired, you can use another function to fetch its expiry_timestamp and confirm whether or not, it is greater than the current timestamp

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