[#] Super random w php

( Ostatnio zmieniony pt., 11/07/2008 - 01:08 )
 
<?php

/**
 * sha1_unique  - 40 character unique hash
 * md5_unique   - 32 character unique hash
 * alnum        - alpha-numeric characters
 * alpha        - alphabetical characters
 * numeric      - digit characters, 0-9
 * nozero       - digit characters, 1-9
 */
function super_random($type = 'alnum', $length = 10) {
  switch ($type) {
    case 'sha1_unique':
      return sha1(uniqid(NULL, TRUE));

    case 'md5_unique':
      return md5(uniqid(NULL, TRUE));

    case 'alnum':
      $pattern = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      break;

    case 'alpha':
      $pattern = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      break;

    case 'numeric':
      $pattern = '0123456789';
      break;

    case 'nozero':
      $pattern = '123456789';
      break;

    default:
      $pattern = (string) $type;
      break;
  }

  $out = '';
  $pattern_size = strlen($pattern);

  for ($i = 0; $i < $length; ++$i) {
    $out .= substr($pattern, mt_rand(0, $pattern_size - 1), 1);
  }

  return $out;
}

echo super_random('alnum', 10) ."\n";   // eOIP6nTjsq
echo super_random('sha1_unique') ."\n"; // c82aae141ac3afc3d7ae3287341da1b9d71b03be
echo super_random('md5_unique') ."\n";  // 0b3fd7feff106eb200362bbc816d5d56
echo super_random('alpha', 10) ."\n";   // WafGLMCVOl
echo super_random('nozero', 10) ."\n";  // 4957853188
echo super_random('numeric', 10) ."\n"; // 7702509099
echo super_random() ."\n";              // 3ADpMU6ZvH

?>
5
Twoja ocena: Brak Średnio: 5 (1 vote)