Ad

Does The Str_random() Function Use Any Time Stamp Like Uniqid() Function?

- 1 answer

I'm working on a API for a mobile app and I want to create a unique token for user validations. Currently i'm using str_random(30) function for that.

Basically I want to know that how str_random() function is working. Does it use any time stamp?

public function generateToken($user_id)
    {
        $randToken = str_random(30);
        if (Token::updateOrCreate([
            'user_id' => $user_id,
        ], [
            'user_id' => $user_id,
            "token"   => $randToken
        ])
        ) {
            return $randToken;
        }

        return "";
    }
Ad

Answer

The str_random() or \Str::random() uses random_byte() to generates cryptographically secure pseudo-random bytes by using OS specific random generator.

So it's even better than using time stamps for randomness, but doesn't guarantee the uniqueness of uniqid.

What you can do for your unique token, is to use JWT (Json Web Token) format. Each token would be unique since at some point it uses the ID of the entity, it has expiration time which make it more secure in case it's leaked, among more benefits....

Ad
source: stackoverflow.com
Ad