note 105587 added to function.mt-rand
| From: | rok dot kralj at rok-kralj dot net | Date: | Tue, 30 Aug 2011 16:12:44 +0000 |
| Subject: | note 105587 added to function.mt-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-182825@lists.php.net to get a copy of this message | ||
This function has limited entrophy. So, if you want to create random string, it will produce only
about 2 billion different strings, no matter the length of the string. This can be serous security
issue if you are using such strings for session indentifiers, passwords etc.
Many times I have wanted to create *propper* base-64 string (containing only printable characters)
of arbitrary length for many purposes. I wrote a function that checks if UNIX random generator is
available and uses in that case. If not, it tries to increase the entrophy by accounting in the
script execution time.
Here is the function, just try it out!
function random($len) {
if (@is_readable('/dev/urandom')) {
$f=fopen('/dev/urandom', 'r');
$urandom=fread($f, $len);
fclose($f);
}
$return='';
for ($i=0;$i<$len;++$i) {
if (!isset($urandom)) {
if ($i%2==0) mt_srand(time()%2147 * 1000000 + (double)microtime() * 1000000);
$rand=48+mt_rand()%64;
} else $rand=48+ord($urandom[$i])%64;
if ($rand>57)
$rand+=7;
if ($rand>90)
$rand+=6;
if ($rand==123) $rand=45;
if ($rand==124) $rand=46;
$return.=chr($rand);
}
return $return;
}
----
Server IP: 91.185.195.14
Probable Submitter: 95.176.219.82
----
Manual Page -- http://www.php.net/manual/en/function.mt-rand.php
Edit -- https://master.php.net/note/edit/105587
Del: integrated -- https://master.php.net/note/delete/105587/integrated
Del: useless -- https://master.php.net/note/delete/105587/useless
Del: bad code -- https://master.php.net/note/delete/105587/bad+code
Del: spam -- https://master.php.net/note/delete/105587/spam
Del: non-english -- https://master.php.net/note/delete/105587/non-english
Del: in docs -- https://master.php.net/note/delete/105587/in+docs
Del: other reasons-- https://master.php.net/note/delete/105587
Reject -- https://master.php.net/note/reject/105587
Search -- https://master.php.net/manage/user-notes.php