Random String Function

Random String Function

A simple function to create a random string.

<?
function generateString ($length = 8)
{
  $string = "";
  $possible = "0123456789bcdfghjkmnpqrstvwxyz";
  $i = 0;
  while ($i < $length) {
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
    $string .= $char;
    $i++;
  }
  return $string;
}
?>

A bit more elegant:

<?
function getUniqueCode($length = 8)
{
$code = md5(uniqid(rand(), true));
if ($length != "") return substr($code, 0, $length);
else return $code;
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *