Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 26
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
W takich dniach, jak ten, nie żałuję, że wykupiłem abonament. Korzystam z porad na tych stronach nawet kilkanaście razy w tygodniu i dzięki nim prace nad stronami dla klientów idą mi o wiele szybciej, a strony wyglądają bardziej profesjonalnie. Nie wiem, jak mogłem wcześniej pracować bez dostępu do porad w tym serwisie!

Wojciech Miszkiewicz

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

mt_rand

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

mt_rand -- Wygeneruj lepszą liczbę losową

Opis

int mt_rand ( [int min, int max] )

Wiele generatorów liczb losowych w starych libc ma niepewne albo nieznane charakterystyki i są powolne. Domyślnie PHP używa generatora liczb losowych z libc w funkcji rand(). Funkcja mt_rand() jest jej zamiennikiem. Używa ona generatora liczb losowych o znanej charakterystyce używając Mersenne Twistera, który generuje liczby losowe czterokrotnie szybciej niż średnio funkcja rand() z glibc.

Jeśli funkcja zostanie wywołana bez opcjonalnych argumentów min i max, funkcja mt_rand() zwróci liczbę pseudolosową z przedziału pomiędzy 0 a RAND_MAX. Jeśli na przykład potrzebujesz liczby losowej z przedziału od 5 do 15 włącznie, użyj mt_rand (5, 15).

Przykład 1. Przykład mt_rand()

<?php
echo mt_rand() . "\n";
echo
mt_rand() . "\n";

echo
mt_rand(5, 15);
?>

Powyższy przykład wyświetli coś podobnego do:

1604716014
1478613278
6

Notatka: Od PHP w wersji 4.2.0 nie ma potrzeby inicjalizować generatora liczb losowych funkcją srand() lub mt_srand(), ponieważ dzieje się to automatycznie.

Notatka: W wersjach przed 3.0.7 argument max znaczył zakres. Aby otrzymać takie same wyniki w tychże wersjach, należy użyć mt_rand (5, 11) aby otrzymać liczbę losową z przedziału od 5 do 15.

Patrz także: mt_srand(), mt_getrandmax() i rand().




User Contributed Notes

ripat at lumadis dot be
08-Nov-2005 05:38

Yet another snippet to generate a password.
<?php
  $acceptedChars
= 'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN0123456789';
 
$max = strlen($acceptedChars)-1;
 
$password = null;
  for(
$i=0; $i < 8; $i++) {
  
$password .= $acceptedChars{mt_rand(0, $max)};
  }
  echo
$password;
?>
I have tried several ways of doing it but this simple one seems to be the fastest.


appelNOSPAM at nr78 dot net
31-Oct-2005 01:18

Phil's code (07-Oct-2005 03:13) + minor improvements in a function (no rocket science):

<?php

  
function gen_passw($len = 8)
   {
      
// define ASCII ranges...
       // See http://www.keller.com/html-quickref/latin1.html
      
$ranges = array
       (
          
1 => array(97, 122), // a-z (lowercase)
          
2 => array(65, 90),  // A-Z (uppercase)
          
3 => array(48, 57// 0-9 (numeral)
      
);
      
$passw = "";
       for (
$i=0; $i<$len; $i++)
       {
          
$r = mt_rand(1,count($ranges));
          
$passw .= chr(mt_rand($ranges[$r][0], $ranges[$r][1]));
       }
       return
$passw;
   }

   echo
gen_passw(6);

?>


fahri at konse dot de
08-Oct-2005 06:12

i did the following, to generate a few random-numbers out of a total amount of numbers, but to create different random-numbers and not double or tripple.
for example i use it to generate 10 random-pics out of 150, and do shurely generate not twice the same...

<?php
$total
6; // available numbers (of pictures)
$randanzahl = 6; //number of random-number to generate out of $total

function checkifdouble($ran,$i) {
       for(
$j=1; $j<$i; $j++) {
               if(
$ran[$j]==$ran[$i]) {
                      
$ergebnis="true";
                       break;
               }
//endif
              
else {
                      
$ergebnis="false";
               }
//endelse
      
} //endfor
return $ergebnis;
}

for (
$i=1; $i<=$randanzahl; $i++) {
      
$ran[$i] = mt_rand(1, $total);
       if (
$i>1) {
               while(
checkifdouble($ran,$i)=="true") {
                      
$ran[$i] = mt_rand(1, $total);
                      
$v=checkifdouble($ran,$i);
                       echo(
$v);
               }
//endif
      
}
       echo(
$ran[$i]."<br>");

}
//enfor
?>

this version is easily for debugging and adaption!
maybe there is a very shorter version...


phil [underscore] ozil at hotmail dot com
07-Oct-2005 03:13

Quit bothering yourselves.
All it takes to create a secure random-generated password is those three lines:

<?php
$pass
= "";
// Generate a 8 char password
for ($i=0; $i<8; $i++)
 
$pass .= chr(mt_rand(35, 126));
?>

Note:
In this example, the character's ASCII values range from 35 to 126.

For character's ASCII codes please check:
http://www.keller.com/html-quickref/latin1.html


frans-jan at van-steenbeek dot net
03-Oct-2005 04:18

My try at generating a reasonably secure password:

<?php
 
function keygen() {
 
$tempstring =
 
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNO
  PQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABC
  DEFGHIJKLMNOPQRSTUVWXYZ!?@#$%&*[]{}();:,<>~+=-_
  /|\\"
;
  for(
$length = 0; $length < mt_rand(10, 15); $length++) {
  
$temp = str_shuffle($tempstring);
  
$char = mt_rand(0, strlen($temp));
  
$pass .= $temp[$char];
  }
  return
$pass;
 }
 echo(
keygen());
 echo(
"\n");
?>

This generates a password of an undefined length (in this case, 10 to 15 chars) consisting of numbers, UPPERCASE letters lowercase letters and a set of signs. I have doubled the chance of number and letters to reduce the confusion with my users.


sean at codeaholics dot com
22-Jul-2005 03:31

Donald at design's implementation repeats the error of demographica.  You really shouldn't generate a number to determine the _type_ of the char, then the char itself.  If security is an issue for you, and you want to maintain as much entropy as possible, you should use a function similar to the one below.  Since this seems to be getting repeated over-and-over, I explained (beat into the ground?) the issue on http://www.codeaholics.com/randomCode.php

The code:
<?php
////
// Returns a random code of the specified length, containing characters that are
// equally likely to be any of the digits, uppercase letters, or  lowercase letters.
//
// The default length of 10 provides 839299365868340224 (62^10) possible codes.
//
// NOTE: Do not call wt_srand().  It is handled automatically in PHP 4.2.0 and above
//      and any additional calls are likely to DECREASE the randomness.
////
function randomCode($length=10){
  
$retVal = "";
   while(
strlen($retVal) < $length){
      
$nextChar = mt_rand(0, 61); // 10 digits + 26 uppercase + 26 lowercase = 62 chars
      
if(($nextChar >=10) && ($nextChar < 36)){ // uppercase letters
          
$nextChar -= 10; // bases the number at 0 instead of 10
          
$nextChar = chr($nextChar + 65); // ord('A') == 65
      
} else if($nextChar >= 36){ // lowercase letters
          
$nextChar -= 36; // bases the number at 0 instead of 36
          
$nextChar = chr($nextChar + 97); // ord('a') == 97
      
} else { // 0-9
          
$nextChar = chr($nextChar + 48); // ord('0') == 48
      
}
      
$retVal .= $nextChar;
   }
   return
$retVal;
}
?>


docey
07-Jul-2005 09:40

if you want an absolute unique id try this,

md5(microtime().data("r").rand(10000, 32000));

this way its almost impossible to generate the same hash
again since the microtime unixtimestamp, the rfc date and
a random number of 5 digits make the changes of having
the same input to create the hash about 22000 posiblities
per milisecond.

so if you can generete 22000 diffrent hashes per
milisecond you might have a double, else you have to wait
another 128 years orso before the same combination can
be generated.

i have run a test om my pc with the possibilties of
generating the same random and with 5 digits it needed
almost 5min before the same number would come again.

this type of hashing can be fairly safe for genereting a
secure session id to keep track that your still talking to
the same client.

i use this in some websites and the performance is barley
affected, although i find the performance diffrence between
rand and mt_rand almost none. use normal rand when you
can and mt_rand only when speed is a must.

one small note to the documentation team, don't know if
here is the right place to ask, but i might be an idea to
place the php version when a function became supported
next to the function name in the listings, now i have to
check each function to see if i can use it in my php version.

just my 2 eurocents,


trojjer at gmail dot com
30-Jun-2005 02:01

To test the "randomisationality" or whatever it's called for this, I tried to devise a simple ol' "Coin Flip Simulator", thus:

<?php

$trials
=($argv[1] >= 1) ? $argv[1] : 100000;
$repeats=($argv[2] > 1) ? $argv[2] : 1;
# command line attributes and their default values

$max=100; # change if necessary -- "bug" on my PC; can't use the var-name in mt_rand()???

function getRnd() { mt_srand(); return mt_rand(0, 100); }
# Rules out possible WinXP bug by re-seeding each time
# (no, I haven't got around to trying any PC alt-OS's yet, ahem.)

$heads=$tails=array(0);
# they're arrays in order to keep track of repeated cycles, if necessary -- see below:

while($repeats > 0) { # sets up countdown from $argv[2]
  
for($n=0; $n<$trials; $n++) { $rnd=getRnd();
       while(
$rnd==$max) {$rnd=getRnd();} # if it's the max number, fetch it again randomly until it's not
      
if($rnd >= 0 && $rnd < $max/2) {$heads[$repeats]++;} }
# "If it's less than the mid-value, add one to the Heads."

$tails[$repeats]=$trials-$heads[$repeats]; #get remaining 'Tail-count' by difference

echo "$repeats:\\n".
 
"{$heads[$repeats]} [". round($heads[$repeats]/$trials*100, 4) ."%] heads\\n".
 
"{$tails[$repeats]} [". round($tails[$repeats]/$trials*100, 4) ."%] tails ($trials trials)\\n\\n";
$repeats--; }

?>

I'm not sure whether or not it's the easiest or most correct way to do it, but it seems to present fairly random results, especially with high numbers of trials. I tried it at 1000000 and beyond, but you don't need any more than the default 100000 to see a "decent" distribution, I think. It'll be "humanly clear" with quite a bit less than that, even.

The $max value doesn't seem to affect the pseudo-random function data, really -- I noticed about the same distributions when using the range of mt_rand(0,2). [0 <= 1 for Head, of course.] Also, does anyone know why it wouldn't let me substitute the variable into the mt_rand() call? I'm using PHP5... I tried casting it as an integer to no avail; in the end I just typed in mt_rand(0, 100) as you can see. Otherwise, it must've been returning null or something -- it was reporting 100.001% Heads, damnit.

Example command line and output:

>php cointoss.php - 3 1000

3:
49895 [49.895%] heads
50105 [50.105%] tails (100000 trials)

2:
50123 [50.123%] heads
49877 [49.877%] tails (100000 trials)

1:
50000 [50%] heads
50000 [50%] tails (100000 trials)

(As you can see, I presume, the $repeat attribute is just in case you wish to compare results. The arrays are assigned in reverse too, and they stop at index [1]. And I swear I witnissed that genuine output for number 1 -- complete 50:50 distribution! lol, it's a good generator all right... Has anyone else stumbled across that moment? Is it more common than I thought for a "pseudo-random" gen?)


mina86 at nospam dot projektcode dot org
25-May-2005 02:00

Re: solenoid at hotmail dot united dot kingdom

In theory method shown by selenoid can lead to infinite loop. The correct method would be:

<?php
$randomNumbers
= array();
for (
$i = 0; i<30; ++$i) $randomNumbers[] = $i;
shuffle($randomNumbers);
for (
$i = 20; $i<30; ++$i) unset($randomNumbers[$i]);
$randomNumbers = array_values($randomNumbers);
?>

The last two lines may be in some cases removed.


corychristison at lavacube dot com
17-Apr-2005 04:46

An advanced Shell/PHP string generator - made for command line:

#!/usr/bin/php -q
<?php

if( $argv[1] == null || $argv[1] <= 0 || !is_numeric($argv[1]) )
{
  
$argv[1] = 10;
}
$limit = $argv[1];

if(
$argv[2] == null )
{
  
$use = array('l', 'u', 'n');
}
else
{
  
$tmp = wordwrap($argv[2], 1, ':', true);
  
$use = explode(':', strtolower($tmp));
}

// USE
  
$feed = array(''); // create array, to avoid any possible errors
  
if( in_array('l', $use) )
   {
      
// lowercase characters [l=lowercase]
      
$feed[] = 'abcdefghijklmnopqrstuvwxyz';
   }
   if(
in_array('u', $use) )
   {
      
// capital characters [u=uppercase]
      
$feed[] = strtoupper('abcdefghijklmnopqrstuvwxyz');
   }
   if(
in_array('o', $use) )
   {
      
// 'other' characters [o=other]
      
$feed[] = ' !@#$%^&*()-+=/\:;{}[]<>?';
   }
   if(
in_array('n', $use) )
   {
      
// numerical characters [n=numbers]
      
$feed[] = '0123456789';
   }

// shuffle the array, appear more random - this is not necessary
  
shuffle($feed);

// store feed into a single string
  
$feed = implode('', $feed);

// loop through and do your stuff
  
for ($i=0; $i < $limit; $i++)
   {
       echo
substr($feed, mt_rand(0, strlen($feed)-1), 1);
   }

// echo out a break :-)
  
echo "\n";

?>

Usage: strgen [length/limit] [USE]

Example #1: strgen 10 loun
// eg. output: ?<ro3:Z$(A

Example #2: strgen 32 ln
// eg. output: gb9ed4w8ynrve08tj1n6zsux30enmjq2

Example #3: strgen 15 uo
// eg. output: @*=:N^T?H>Z;MMV

This little utility is great for password generation, it allows you to include or exclude the use of lowercase characters, capitcal characters, 'other' characters, and numbers "on the fly!"

Have fun!


nowhere at where dot net
16-Apr-2005 11:46

Allows characters 0-9, a-z
Weighted (and tested) ok.

<?php
function generate_string ($length = 20)
{
  
$nps = "";
   for(
$i=0;$i<$length;$i++)
   {
      
$nps .= chr( (mt_rand(1, 36) <= 26) ? mt_rand(97, 122) : mt_rand(48, 57 ));
   }
   return
$nps;
}
?>


solenoid at hotmail dot united dot kingdom
28-Feb-2005 12:00

Sometimes you need a bunch of unique random numbers and they have to be in a certain small range, here's a simple script that uses an array to remember the numbers generated before:

<?php

$randomNumbers
= array(); // storage array
for ($i=0;$i<20;$i++) {
  
$random = mt_rand(0,30);
   while(
in_array($random,$randomNumbers)) {
      
$random = mt_rand(0,30);    }
  
array_push($randomNumbers,$random);
   echo
$random;
}

?>

This way, when the while() function finds that the generated number is already in the storage array, it will automatically generate another one until no same number is found, thus eliminating any possibilities of having multiple same numbers... but still random.


ketan at vnhsystems dot com
02-Feb-2005 04:07

mt_rand() was generating the same number on Solaris SPARC so I switched to rand() and worked fine.


mskala at ansuz dot sooke dot bc dot ca
24-Jan-2005 12:47

Running the output of Mersenne Twister through an unkeyed secure hash is NOT a good way to make it secure, because it'll still have a relatively small internal state which, if recovered, would allow reproduction of the keystream.  A better idea would be to encrypt the output with a keyed encryption algorithm - but if you were going to do that, you wouldn't need a psuedorandom number generator at all, because a counter would be just as good.


paulo at icreations dot com dot br
07-Jan-2005 01:28

Warning! Some times in windows platform (2000 and XP) mt_rand generates the same number. It happens to me in 3 machines (1xW2000 and 2xWXP) and in another two XP doesnt happens.

PHP Version: 4.3.4
All XP machines with SP2 and all 2000 machines with SP1.

I have to use a mt_srand function to correct this issue.

Hope this help someone.


russ at garrett dot co dot uk
09-Sep-2004 10:50

That's *up to* four times faster. Depending on how rand() is implemented in your libc. The point is that mt_rand() has known performance characteristics, wheras rand() doesn't because it varies from system to system.


Julien CROUZET jucrouzet_at_cpan.org
08-Sep-2004 01:08

mt_rand is a better random method,
BUT
mt_rand() is NOT four time faster than rand()

$> time echo "<?php  $i = 1000000; while($i--) { rand(0,10); } ?>" | php
php  1.68s user 0.01s system 99% cpu 1.693 total

$> time echo "<?php  $i = 1000000; while($i--) { mt_rand(0,10); } ?>" | php
php  1.69s user 0.02s system 100% cpu 1.708 total

time echo "<?php  $i = 1000000; while($i--) { rand(0,100000); } ?>"
php  1.71s user 0.00s system 99% cpu 1.713 total

time echo "<?php  $i = 1000000; while($i--) { mt_rand(0,100000); } ?>" | php
php  1.72s user 0.02s system 100% cpu 1.726 total


timr at onlinehome dot de
13-Aug-2004 01:24

The correct address of the inventor's FAQ is (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/efaq.html). They state that Mersenne Twister may be used for cryptography if you do some post-processing:

"Mersenne Twister is not cryptographically secure. (MT is based on a linear recursion. Any pseudorandom number sequence generated by a linear recursion is insecure, since from sufficiently long subsequence of the outputs, one can predict the rest of the outputs.)

To make it secure, you need to use some Secure Hashing Algorithm with MT. For example, you may gather every eight words of outputs, and compress them into one word (thus the length of the output sequence is 1/8 of the original one)."


charles (at) storagereview (dot) com
19-Jun-2004 08:34

Note that the MT random number generator is not recommended for use in encryption.
See http://www.math.keio.ac.jp/~matumoto/efaq.html


mina86 at tlen dot pl
09-Apr-2004 03:23

I've written simple library with functions generating random strings which supports /dev/urandom special device. It's not yet tested very well but should work ;) CVS entry's available here: http://cvs.projektcode.org/view.cgi/miki/include/random.inc.php (if it's no longer there and you really need it email me (use descriptive subject and no attachemnts so you're message won't be treated as a spam :P ))


11-Feb-2004 02:27

Here is a example of a very small, compact, quite random-random string generator. It will make a string with uppercase & lowercase letters, with numbers. You simply need to set $len in the for() structure, and then the string will be in $r.  It has been designed for size, while it's still quite fast.  Mind the wrapping, it should be 1 line.

<?php
for($len=8,$r='';strlen($r)<$len;$r.=chr(!mt_rand(0,2)?
mt_rand(48,57):(!mt_rand(0,1)?mt_rand(65,90):mt_rand
(97,122))));
?>

Armond Carroll


tmx at ntlworld dot com
06-Dec-2003 10:26

When using this function, it doesn't matter which order the numbers go in.

     mt_rand(16,5)

works just as well as

     mt_rand(5,16)

Which can be useful if you are pulling values from a database, that could be negative or positive.

     mtrand(0,$anyinteger)

Hope this helps someone


daeken_9999 at yahoo dot com
08-Jul-2003 11:44

This is a fixed version of the gaussrand() function defined in a note above.

<?php
function gaussrand()
{
   static
$V2, $V1, $S;
   static
$phase = 0;
   if (
phase == 0)
   {
       while (
$S >= 1 || $S == 0)
       {
          
$V1 = 2 * (rand() / getrandmax()) - 1;
          
$V2 = 2 * (rand() / getrandmax()) - 1;
          
$S = $V1 * $V1 + $V2 * $V2;
       }
      
$X = $V1 * sqrt(-2 * log($S) / $S);
   }
   else
      
$X = $V2 * sqrt(-2 * log($S) / $S);
  
$phase = 1 - $phase;
   return
$X;
}
?>


joeldg at listbid.com
17-Jun-2003 04:14

/* This function return a gaussian distribution of floating-point
 * numbers.  This implementation is recommenden by D. Knuth, but due
 * originally to Marsaglia.
 *
 * Taken from the Comp.lang.c FAQ, maintained by Steve Summit.
 * ported to php from c by Joel De Gan
 * http://lucifer.intercosmos.net
 */

function gaussrand(){
   #static double V1, V2, S;
   $phase = 0;
   #double X;
   if (phase == 0) {
       while ($S >= 1 || $S == 0){
           $U1 = (double) rand() / 2147483647;
           $U2 = (double) rand() / 2147483647;
           $V1 = 2 * $U1 - 1;
           $V2 = 2 * $U2 - 1;
           $S = $V1 * $V1 + $V2 * $V2;
       };
       $X = $V1 * sqrt(-2 * log($S) / $S);
   }
   else {
       $X = $V2 * sqrt(-2 * log($S) / $S);
   }
   $phase = 1 - $phase;
   return $X;
}


jsheets at shadonet dot com
04-Jun-2003 10:49

The following function will create a random base64 encoded key, this is very useful for password reset schemes or anything where you want a random string.  To compare the string either compare the base64 encoded value or base64_decode it and compare that.

I do not use md5 because md5 results in only 1-9 and a-f in the string or 32^16 possibilities, by using the extended ASCII table and shuffling the array I am able to get a minimum of 32^127 possibilities with a 32 character string, using a longer string will make your value harder to guess still. A lot of machiens will have 32^255 possibilities in a decoded string.

function MakeResetKey($min_length = 32, $max_length = 64)
{
   $key = '';

   // build range and shuffle range using ASCII table
   for ($i=0; $i<=255; $i++) {
     $range[] = chr($i);
   }

   // shuffle our range 3 times
   for ($i=0; $i<=3; $i++) {
     shuffle($range);
   }

     // loop for random number generation
   for ($i = 0; $i < mt_rand($min_length, $max_length); $i++) {
     $key .= $range[mt_rand(0, count($range))];
   }

   $return = base64_encode($key);

   if (!empty($return)) {
     return $return;
   } else {
     return 0;
   }
}


donald at design dot net
07-Apr-2003 08:18

here's a REALLY simple random string generator, not as long and complicated as the others, but the same in theory:

function randstr($length = 16) {
   mt_srand((double)microtime()*10000);
   for($i=0;$i<$length;$i++) {
       $x = mt_rand(1,3);
       $str .= (($x == 1) ? chr(mt_rand(48,57)) : (($x == 2) ? chr(mt_rand(65,90)) : chr(mt_rand(97,122))));
   }
   return $str;
}


michael at something hotmail dot com
18-Nov-2002 12:49

An answer to demogracia:

Your first function "simpleRandString" is perfect, but the second function "randString" has a flaw: since you use the random generator to go into one of the three cases, every case will be used 1/3 of the time. Since case 1 has less possibilites than the others (10 vs. 26 and 26), the output can be more easily guessed: numbers will appear more often than average.

Here is the same function without this flaw:
function randString($length=16)
{
   $newstring="";
   if($length>0)
   {
       while(strlen($newstring)<$length)
       {
           $randnum = mt_rand(0,61);
           if ($randnum < 10)
               {$newstring.=chr($randnum+48);}
           elseif ($randnum < 36)
               {$newstring.=chr($randnum+55);}
           else
               {$newstring.=chr($randnum+61);}
       }
   }
   return $newstring;
}

You can make it a bit faster by not relying on "strlen" for every pass:
function randString($length=16)
{
   $newstring="";
   if($length>0)
   {
       while(strlen($newstring)<$length)
       {
           $randnum = mt_rand(0,61);
           if ($randnum < 10)
               {$newstring.=chr($randnum+48);}
           elseif ($randnum < 36)
               {$newstring.=chr($randnum+55);}
           else
               {$newstring.=chr($randnum+61);}
       }
   }
   return $newstring;
}


rugby at flipp dot net
10-Jul-2002 06:03

Just a small note for those zealots who want to avoid overseeding (which reduces randomness).

I have this small function to solve to get the best of both worlds:

(note the global variable)

----------------
$already_random = false;
function mt_seed(){
   global $already_random;
   if ($already_random) {
     list($usec, $sec) = explode(' ', microtime());
     mt_srand((float) $sec + ((float) $usec * 100000););
   }
$already_random=true;
}   
mt_seed();
$dice=mt_rand(1,6);
----------------

dead easy of course, but it might help some people.

If you are not sure what everybody is on about on this page, you can use this funtion (+global variable!) instead of make_seed(). Its a little better.


tom at globalmedia dot org
01-May-2002 09:24

To return a random decimal value between 0 and 1:
$randval=mt_rand()/mt_getrandmax();


guywhous at esphp dot com
11-Mar-2002 04:09

On an Apache 1.3.3 server, the seed mt_rand() uses resets to the same value every time the PHP file is uploaded.  This means that if mt_rand(1,500) returns 273 the first time it is used in your PHP file, it will return 273 again if you re-upload this file.  You have been warned.


demogracia at metropoliglobal dot com
02-Mar-2002 09:38

//
// Generates a random string with the specified length
// Chars are chosen from the provided [optional] list
//
function simpleRandString($length=16, $list="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"){
   mt_srand((double)microtime()*1000000);
   $newstring="";

   if($length>0){
       while(strlen($newstring)<$length){
           $newstring.=$list[mt_rand(0, strlen($list)-1)];
       }
   }
   return $newstring;
}

//
// Generates a random string with the specified length
// Includes: a-z, A-Z y 0-9
//
function randString($length=16){
   mt_srand((double)microtime()*1000000);
   $newstring="";

   if($length>0){
       while(strlen($newstring)<$length){
           switch(mt_rand(1,3)){
               case 1: $newstring.=chr(mt_rand(48,57)); break;  // 0-9
               case 2: $newstring.=chr(mt_rand(65,90)); break;  // A-Z
               case 3: $newstring.=chr(mt_rand(97,122)); break; // a-z
           }
       }
   }
   return $newstring;
}


psychoborg at yahoo dot com
31-Jan-2002 09:34

ok, an update to my last comment

well, the rand function works, but looks like it has a limitation to it.

look at this :
function calcres($number)
{
   global $Supplies;
   srand ((double) microtime() * 1000000);
       $retval = 0;
   $a = 0;
   if ($a!=$number)
   {
       do
       {
           $a++;
         #  $tmp = rand(0,3+
         # the rand is limited in the function,  Especcially with the current formula that im using here. but the fix is quite simple. just change the rand to mt_rand this will increase your random findings and stablize your php program,
($supplies+$retval));
           if ($tmp<20) $retval++;
       }while($a<$number);
   }
   return $retval;
}

This function will work best with the mt_rand runction and not only that, it is most defanitly more stable. meaning you will not hit the limitation that will cause the SQL event out of range error.


12-Jan-2002 07:33

There is a intresting article on Developers resources about
Pseudo-random PHP functions and truly random number generators.
http://www.developers-resources.com/stories.php?story=01/12/03/3988084

They have wrote a function that randomly retrieves a random number. Either generated by the computer pseudo-randomly or from one of two truly random number sites.


amcclung at stetson dot edu
18-Apr-2001 10:27

Here's an elegant way of generating a random float value within a certain range:

$range = $upperBound-$lowerBound;
$num = $lowerBound + $range * mt_rand(0, 32767)/32767;

You should now have a floating point number between your $lowerBound (i.e. 0.5) and $upperBound (0.75) values.


gerwout at minso dot nl
27-Mar-2001 05:29

Don't forget to do mt_srand() before the mtrand() or you wil get the same values every time you'll go back to the same page.<br>Not when you refresh the page, only when you open the page in a new browserwindow and the history is empty.


mrdlinux at yahoo dot com
21-Jul-2000 07:02

And for those who prefer scaling:

mt_rand() / RAND_MAX * (Max - Min) + Min;


 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt