How do i make a token expire time

蹲街弑〆低调 提交于 2019-12-20 04:24:36

问题


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:

function token($length = 40) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $token = 12000;
    $token = srand(floor(time() / $token));
    for ($i = 0; $i < $length; $i++) {
        $token .= $characters[rand(0, $charactersLength - 1)];
    }
    return $token;
}

回答1:


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



来源:https://stackoverflow.com/questions/44164870/how-do-i-make-a-token-expire-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!