November 23, 2010

Create a Randomly Generated String of Arbitrary Length in PHP

Today I realized that I needed to create a method for generating a pseudo-random string from a constrained set of symbols. Rather than immediately consult Google for code, I decided to come up with the function myself. Hopefully it's helpful for some folks out there who opt to Google :)

Oh, and if you see anything that can be improved with this code please leave a comment!

//GetCharacterPool returns a constrained set of ASCII characters, consisting of
//A-Za-z0-9 and selected symbols.
function GetCharacterPool(){

      $charpool = array( 33, 35, 36, 37, 38, 94, 95, 126 );
     
      for($i=48;$i<=57;$i++){
          $charpool[] = $i;
      }
      for($i=64;$i<=90;$i++){
          $charpool[] = $i;
      }
      for($i=97;$i<=122;$i++){
          $charpool[] = $i;
      }
      return $charpool;
}


//GenerateRandomString generates a pseudo-random string of $length characters.
function GenerateRandomString($length){

      $rstring = "";
      $pool = GetCharacterPool();
      $rmin = 0;
      $rmax = count($pool)-1;


      for($i=0;$i<$length;$i++){
          $rnum = mt_rand($rmin,$rmax);
          $c = chr($pool[$rnum]);
          $rstring.= $c;
     }

     return $rstring;
}
Post a Comment