Re: what's wrong with this while loop?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



the problem with your loop is that after php enters it, it can't get out because there is no break, nor a way to turn the expression to false.

Normally, you have a loop which always evaluates to TRUE, and when it doesn't, you want to quit. And even when this is not how you did it, eg with while(true){ ... }, then you can bail out using break.

However, you did none of those here.
Your loop starts with
while($tot < $sum) {
	[...]
}
and doesn't in any way modify the value of any of both inside the (double!) loop, nor does it ever break. So, you're stuck with an eternal loop as a result.

Besdies that, I'm wondering what you need the while()-loop for anyway, since it's utterly useless in your code. An easier way would be to code it like this:

$rand_pass = '';
for ($i = 0; $i < $length; $i++){
   $rand_pos  = rand(0, $rand_max);
   $rand_key .= $key_chars{$rand_pos};
}

$somecontent = "new key: $rand_pass\n";
echo $somecontent;

bo wrote:
Following my code is to write a 15digit random generated password into a file named test.txt. I was trying to keep it random generating 100 passwords and be written into test.txt by using a while loop, however, the result is strange.

Take a look at the code (most of it is from php.net) and what's wrong with this while loop? besides, if I generate a large sum of passwords,say 50 million, will it be repetitive?
Thank you!


<?php
/*
<meta HTTP-EQUIV="REFRESH"
content="1; url=http://svr/rand.php";>
*/

$length    = 15;
$sum       = 100;
$key_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$rand_max  = strlen($key_chars) - 1;
$filename  = 'test.txt';

$tot=0;
while($tot < $sum){
for ($i = 0; $i < $length; $i++){

   $rand_pos  = rand(0, $rand_max);
   $rand_key[] = $key_chars{$rand_pos};
}


$rand_pass = implode('', $rand_key);
$somecontent = "$tot $rand_pass\n";
echo $somecontent;


$filename = 'test.txt';

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

   // In our example we're opening $filename in append mode.
   // The file pointer is at the bottom of the file hence
   // that's where $somecontent will go when we fwrite() it.
   if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
   }

   // Write $somecontent to our opened file.
   if (fwrite($handle, $somecontent) === FALSE) {
       echo "Cannot write to file ($filename)";
       exit;
   }

   echo "Success, wrote ($somecontent) to file ($filename)";

   fclose($handle);

} else {
   echo "The file $filename is not writable";
}

$tot++;
}

?>

--
PHP Windows Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [PHP Users]     [PHP Database Programming]     [PHP Install]     [Kernel Newbies]     [Yosemite Forum]     [PHP Books]

  Powered by Linux