note 95683 deleted from function.mt-rand by cmb
| From: | cmb@php.net | Date: | Sun, 19 Jan 2020 08:41:02 +0000 |
| Subject: | note 95683 deleted from function.mt-rand by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213921@lists.php.net to get a copy of this message | ||
Note Submitter: armencho at gmail dot com
----
The following function generates a string of arbitrary length (with limitations), composed of random
PHP characters (i.e. each an 8-bit value - a byte). Suitable for generating random session strings.
Encode as Base64 to transmit over network, where required.
** The function is pretty much one of the fastest (if not THE fastest) methods of generating random
strings, as opposed to numerous examples given on this page which go about with char-by-char
generation. Sloppy benchmarks estimate a factor of 10 speedup. Keep your websites lean, people. **
The only thing to keep in mind is that, by design, it outputs 8-bit characters, and thus the
generated string is not automatically suitable for transmission with various network protocols,
unless altered, f.e. URL- or Base64- encoded. Also, again by design, the length of the string is a
multiple of 4 characters/bytes. The version below produces a 24 character long string. This will
also give you a clean input to get a 32 character long Base64 encoded variant of it.
<?php
function gen_rand_str_24()
{
return pack('N6', mt_rand(), mt_rand(), mt_rand(),
mt_rand(), mt_rand(), mt_rand());
}
?>
I leave it an exercise to the reader to write a generic (i.e. arbitrary double word length, not 6
dwords as in above) version of it.