1

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 "";
    }
  • Not sure about the specific question you are asking, but https://stackoverflow.com/questions/1846202/php-how-to-generate-a-random-unique-alphanumeric-string may be a better solution. – Nigel Ren Oct 28 '19 at 08:26

2 Answers2

2

I searched for Str::random() method in laravel api: https://laravel.com/api/5.8/Illuminate/Support/Str.html#method_random

This is exact code on github for random string generation: https://github.com/laravel/framework/blob/5.8/src/Illuminate/Support/Str.php#L323

    /**
     * Generate a more truly "random" alpha-numeric string.
     *
     * @param  int  $length
     * @return string
     */
    public static function random($length = 16)
    {
        $string = '';
        while (($len = strlen($string)) < $length) {
            $size = $length - $len;
            $bytes = random_bytes($size);
            $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
        }
        return $string;
    }

As I see it doesn't use any timestamp for random string generation

Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40
2

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....

N69S
  • 16,110
  • 3
  • 22
  • 36