phplaravelrandomlaravel-8short-url

Is the str::random() function in Laravel reliable for short URL?


I'm trying to create a simple url shortener in my Laravel project. I want to use only lowercase and uppercase letters and numbers as short url addresses. (For example: sD7hY6g) Is there a possibility that "Str::random()" function under "Illuminate\Support\Str" class in Laravel returns anything other than these characters? Can I trust this function or do I need to create my own custom function?

(In addition, whichever function I use, I check whether the code is already in the database before recording.)

Thank you to everyone who answered in advance.


Solution

  • Should you trust Str::random() to always return an alpha-numeric string? Yes.

    The function normalizes its output by encoding to base 64 number. The 64 symbols that represent a base 64 number are ABCDEFGHIJKLMNOPQRSTUVWXYVabcdefghijklmnopqrstuvwxyz0123456789+\ and = for padding.

    The function also replaces \+= to empty (white spaces), meaning that the only possible output for Str::random() are amongst ABCDEFGHIJKLMNOPQRSTUVWXYVabcdefghijklmnopqrstuvwxyz0123456789.


    Laravel 5+'s Illuminate\Support\Str@random

    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;
    }