You can use :

sha1(time())

Explanation: sha1 is hash function, and most important characteristic of hash function is that they never produce the same hash of different string, so as time() is always unique in theory sha1(time()) will always give you unique string with fixed width.

EDITED:

You can use you function but before giving token you can connect to database and check if token exists, if exists generate new token, if not exists give hin this token. This mechanism will give you unique tokens.

Answer from fico7489 on Stack Overflow
🌐
Laravel.io
laravel.io › forum › 04-08-2014-create-unique-alphanumeric-random-string-in-id-column
Create unique alphanumeric random string in "id" column | Laravel.io
Php has its own randomstring generator. You will just need to put a manual check if it exists already. If not try to create another random string. This should work, however I would not quite recommend it.
🌐
CopyProgramming
copyprogramming.com › howto › php-create-a-random-alphanumeric-in-laravel-php
Php: Generating a random alphanumeric code in Laravel using PHP
May 15, 2023 - 'main' => [ 'salt' => 'your-salt-string', 'length' => '6', 'alphabet' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ], ... How to generate a random, unique, alphanumeric string in PHP, Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in ...
Top answer
1 of 16
689

PHP 7 standard library provides the random_bytes($length) function that generate cryptographically secure pseudo-random bytes.

Example:

$bytes = random_bytes(20);
var_dump(bin2hex($bytes));

The above example will output something similar to:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"

More info: http://php.net/manual/en/function.random-bytes.php

PHP 5 (outdated)

I was just looking into how to solve this same problem, but I also want my function to create a token that can be used for password retrieval as well. This means that I need to limit the ability of the token to be guessed. Because uniqid is based on the time, and according to php.net "the return value is little different from microtime()", uniqid does not meet the criteria. PHP recommends using openssl_random_pseudo_bytes() instead to generate cryptographically secure tokens.

A quick, short and to the point answer is:

bin2hex(openssl_random_pseudo_bytes($bytes))

which will generate a random string of alphanumeric characters of length = $bytes * 2. Unfortunately this only has an alphabet of [a-f][0-9], but it works.


Below is the strongest function I could make that satisfies the criteria (This is an implemented version of Erik's answer).
function crypto_rand_secure(max)
{
    $range = min;
    if ($range < 1) return $min; // not so random...
    $log = ceil(log($range, 2));
    $bytes = (int) ($log / 8) + 1; // length in bytes
    $bits = (int) $log + 1; // length in bits
    $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
    do {
        $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
        rnd & $filter; // discard irrelevant bits
    } while (range);
    return rnd;
}

function getToken($length)
{
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet.= "0123456789";
    $max = strlen($codeAlphabet); // edited

    for (i < $length; $i++) {
        $token .= $codeAlphabet[crypto_rand_secure(0, $max-1)];
    }

    return $token;
}

crypto_rand_secure(max) works as a drop in replacement for rand() or mt_rand. It uses openssl_random_pseudo_bytes to help create a random number between max.

getToken($length) creates an alphabet to use within the token and then creates a string of length $length.

Source: https://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php#104322

2 of 16
346

Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular, rand() and uniqid() are not cryptographically secure random number generators. See Scott's answer for a secure alternative.

If you do not need it to be absolutely unique over time:

md5(uniqid(rand(), true))

Otherwise (given you have already determined a unique login for your user):

md5(uniqid($your_user_login, true))
🌐
Stillat
stillat.com › blog › 2017 › 12 › 06 › laravel-5-string-helpers-generating-random-strings
Laravel 5 String Helpers: Generating Random Strings » Stillat
The random helper method in Laravel generates a random string of the specified length. It uses the OpenSSL function openssl_random_pseudo_bytes and requires the OpenSSL extension to be installed.
🌐
Medium
medium.com › @harrisrafto › enhance-your-string-manipulation-with-str-random-in-laravel-ea3a3ac29f49
Enhance your string manipulation with Str::random() in Laravel | by Harris Raftopoulos | Medium
July 8, 2024 - In this example, Str::random(16) generates a random string of 16 characters. The resulting string consists of random alphanumeric characters.
Find elsewhere
🌐
Laravel Daily
laraveldaily.com › post › generate-random-strings-laravel-helper-methods
Generate Random Strings with Laravel: Helper Methods
Another option is to combine random_bytes() and bin2hex() PHP functions to generate a 20 character string. ... For a random number, the mt_rand() could be used. The default minimum value is zero, and the maximum value is generated by mt_getrandmax.
🌐
DEV Community
dev.to › codeanddeploy › generate-random-string-in-php-j9e
Generate Random String in PHP - DEV Community
May 1, 2023 - <?php function randomString($length = 10) { // Set the chars $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Count the total chars $totalChars = strlen($chars); // Get the total repeat $totalRepeat = ceil($length...
🌐
GitHub
gist.github.com › irazasyed › 5382685
PHP: Generate random string · GitHub
PHP: Generate random string. GitHub Gist: instantly share code, notes, and snippets.
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-generate-a-random-unique-alphanumeric-string-in-php
How to generate a random, unique, alphanumeric string in PHP - GeeksforGeeks
July 4, 2024 - ... <?php function generateRan... $prefix), 0, $length); return $randomString; } // Example usage $randomString = generateRandomString(6); echo $randomString; // Output: Random alphanumeric string of length 6 ?>...
🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-generate-random-alphanumeric-string-in-phpexample.html
How to Generate Random Alphanumeric String in PHP? - ItSolutionstuff.com
May 14, 2024 - $randomString = substr( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,mt_rand( 0 ,50 ) ,2 ) .substr( md5( time() ), 1,3); ... I hope it can help you... ... I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com.
🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-generate-random-unique-string-in-laravel-5example.html
How to Generate Random Unique String in Laravel? - ItSolutionstuff.com
April 16, 2024 - Laravel provide several string helper that way we can use it easily like str_limit, str_plural, str_finish, str_singular etc. If you need to generate unique random string then you can use str_random() helper of Laravel.
🌐
Weblance-online
weblance-online.com › home › website › laravel › using laravel helper methods to generate random strings
Using Laravel Helper Methods To Generate Random Strings - Weblance Online Solutions
June 19, 2024 - The str_random() method in Laravel can be used to easily generate random strings · The str_random() method can be used to generate random alphanumeric strings
Top answer
1 of 7
87

str_random (Str::random()) tries to use openssl_random_pseudo_bytes which is a pseudo random number generator optimized for cryptography, not uniqueness. If openssl_random_pseudo_bytes is not available, it falls back to quickRandom():

public static function quickRandom($length = 16)
{
    $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
}

In my opinion quickRandom code is not reliable for uniqueness nor cryptography.

Yes, having openssl_random_pseudo_bytes and using 32 bytes is almost impossible to see a collision, but it's still possible. If you want to make sure your strings/numbers will be unique (99.99%), you better use a UUID function. This is what I normally use:

/**
 * 
 * Generate v4 UUID
 * 
 * Version 4 UUIDs are pseudo-random.
 */
public static function v4() 
{
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

    // 32 bits for "time_low"
    mt_rand(0, 0xffff), mt_rand(0, 0xffff),

    // 16 bits for "time_mid"
    mt_rand(0, 0xffff),

    // 16 bits for "time_hi_and_version",
    // four most significant bits holds version number 4
    mt_rand(0, 0x0fff) | 0x4000,

    // 16 bits, 8 bits for "clk_seq_hi_res",
    // 8 bits for "clk_seq_low",
    // two most significant bits holds zero and one for variant DCE1.1
    mt_rand(0, 0x3fff) | 0x8000,

    // 48 bits for "node"
    mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}

It generates a VALID RFC 4211 COMPLIANT version 4 UUID.

Check this: https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions

2 of 7
75

you can use this

use Illuminate\Support\Str;

$random = Str::random(40);
🌐
Medium
medium.com › @randomstr › random-string-generation-in-php-and-its-frameworks-bb4b2f1bbce6
Random String Generation in PHP and Its Frameworks | by Random STR | Medium
December 1, 2023 - This function uses random_bytes, ... PHP framework, provides a more straightforward method to generate random strings using the Str helper:...