PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

后端 未结 28 2231
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 22:20

How would it be possible to generate a random, unique string using numbers and letters for use in a verify link? Like when you create an account on a website, and it sends y

28条回答
  •  温柔的废话
    2020-11-21 23:03

    Here is what I'm using on one of my projects, it's working great and it generates a UNIQUE RANDOM TOKEN:

    $timestampz=time();
    
    function generateRandomString($length = 60) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
    
    
    $tokenparta = generateRandomString();
    
    
    $token = $timestampz*3 . $tokenparta;
    
    echo $token;
    

    Please note that I multiplied the timestamp by three to create a confusion for whoever user might be wondering how this token is generated ;)

    I hope it helps :)

提交回复
热议问题