Generating Random, Unique Alphanumeric Strings
In various applications, such as account verification links, it's crucial to generate unique and random strings consisting of numbers and letters. Here's how you can achieve this in PHP:
PHP 7
PHP 7 introduces the random_bytes($length) function to provide cryptographically secure pseudo-random bytes. An example:
$bytes = random_bytes(20); var_dump(bin2hex($bytes));
This will produce an output like:
string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
PHP 5 (Outdated)
For PHP 5, it's recommended to utilize openssl_random_pseudo_bytes() instead, which generates cryptographically secure tokens. A simple solution:
bin2hex(openssl_random_pseudo_bytes($bytes))
More Secure Approach
To enhance security, the following function can generate a random, unique alphanumeric string within a specified length range:
function getToken($length) { $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; $max = strlen($codeAlphabet); // edited for ($i=0; $i < $length; $i ) { $token .= $codeAlphabet[crypto_rand_secure(0, $max-1)]; } return $token; }
This approach incorporates crypto_rand_secure($min, $max) as a drop-in replacement for rand() or mt_rand(), utilizing openssl_random_pseudo_bytes to guarantee randomness.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3