note 95683 added to function.mt-rand
| From: | armencho at gmail dot com | Date: | Fri, 15 Jan 2010 15:59:31 +0000 |
| Subject: | note 95683 added to function.mt-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-165006@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 128.39.198.38
Probable Submitter: 217.14.4.149
----
Manual Page -- http://www.php.net/manual/en/function.mt-rand.php
Edit -- https://master.php.net/note/edit/95683
Del: integrated -- https://master.php.net/note/delete/95683/integrated
Del: useless -- https://master.php.net/note/delete/95683/useless
Del: bad code -- https://master.php.net/note/delete/95683/bad+code
Del: spam -- https://master.php.net/note/delete/95683/spam
Del: non-english -- https://master.php.net/note/delete/95683/non-english
Del: in docs -- https://master.php.net/note/delete/95683/in+docs
Del: other reasons-- https://master.php.net/note/delete/95683
Reject -- https://master.php.net/note/reject/95683
Search -- https://master.php.net/manage/user-notes.php