Jump to content

Random characters snippet not working... But Zend says it ok?


notepad

Recommended Posts

Hey, I am trying to make a random character snippet... This is what I have come-up with so far:

 

<?php

  /* Random String of 8 Characters */

  define("ALPHA", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890");
  define("LENGTH", "8");
  for($i=0;$i< LENGTH;$i++) {
    define("RANDOM", ALPHA(rand(0,61)));
  }
  
  echo RANDOM;
  
?>

 

I did an error check with Zend Studio and the script reads fine, but it doesn't output anything. Can someone give me a hand?

 

btw, I am using PHP 5.

 

~ Notepad

You cannot use define within a loop. define creates constants, constants cannot be changed.

 

Also, this line...

 

define("LENGTH", "8");

 

should be....

 

define("LENGTH", ;

 

Just use variables instead of constants and your code should work.

So basically, I think:

 

for($i=0;$i< LENGTH;$i++) {

    $random .= ALPHA(rand(0,61));

  }

 

echo $random;

 

I think that will work.

 

or you could just use this:

 

<?php
$alpha = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
define("LENGTH", "8");
for($i=0;$i< LENGTH;$i++) {
  $random .= $alpha[rand(0,61)];
  }
echo $random;
?>

Guest prozente

<?php
/* Random String of 8 Characters */
$ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
$RANDOM = '';

define('LENGTH', ;

for($i=0;$i< LENGTH;$i++) {
  $RANDOM .= $ALPHA{rand(0,strlen($ALPHA)-1)};
}

echo $RANDOM;

?>

 

Thanks for the replies, I will try your suggestions. But I think I have it figured out. Here is my new code:

 

<?php

// Random string of 12 characters

define("RANDOM", substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'), 0, 12));

echo RANDOM;

echo "<br />";

echo RANDOM;

?>

 

I did the echo twice to make sure that when I called the RANDOM a second time it wouldn't be a new character set, its not =).

 

~ Notepad

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.