Skip to content

Instantly share code, notes, and snippets.

@itwondersteam
Last active April 7, 2021 14:02
Show Gist options
  • Save itwondersteam/cc090f355b39935d69d2cf0507c88621 to your computer and use it in GitHub Desktop.
Save itwondersteam/cc090f355b39935d69d2cf0507c88621 to your computer and use it in GitHub Desktop.

Laravel Str Generate a more truly "random" alpha-numeric 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;
    }

Example

  • cryptographically secure random alphanumeric string that utilizes all characters from a to z
  • random_bytes() only make use of hexadecimal character
function secure_random_string($length) {
    $random_string = '';
    for($i = 0; $i < $length; $i++) {
        $number = random_int(0, 36);
        $character = base_convert($number, 10, 36);
        $random_string .= $character;
    }
 
    return $random_string;
}
 
// Output: 07y1s10prb8
echo secure_random_string(10);
 
// Output: d9bcwoo7pc
echo secure_random_string(10);
 
// Output: 6llfxe4pvm
echo secure_random_string(10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment