One-line PHP random string generator?

2019-01-31 03:07发布

I am looking for the shortest way to generate random/unique strings and for that I was using the following two:

$cClass = sha1(time());

or

$cClass = md5(time());

However, I need the string to begin with an an alphabet character, I was looking at base64 encoding but that adds == at the end and then I would need to get rid of that.

What would be the best way to achieve this with one line of code?


Update:

PRNDL came up with a good suggestions wich I ended up using it but a bit modified

echo substr(str_shuffle(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ),0, 1) . substr(str_shuffle(aBcEeFgHiJkLmNoPqRstUvWxYz0123456789),0, 31)

Would yield 32 characters mimicking the md5 hash but it would always product the first char an alphabet letter, like so;

solution 1

However, Uours really improved upon and his answer;

substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1).substr(md5(time()),1);

is shorter and sweeter

The other suggestion by Anonymous2011 was very awesome but the first character for some reason would always either M, N, Y, Z so didnt fit my purposes but would have been the chosen answer, btw does anyone know why it would always yield those particular letters?

Here is the preview of my modified version

echo  rtrim(base64_encode(md5(microtime())),"=");

runner up

标签: php random
16条回答
老娘就宠你
2楼-- · 2019-01-31 03:15

I use this function

usage:

 echo randomString(20, TRUE, TRUE, FALSE);

  /**
   * Generate Random String
   * @param Int Length of string(50)
   * @param Bool Upper Case(True,False)
   * @param Bool Numbers(True,False)
   * @param Bool Special Chars(True,False)
   * @return String  Random String
   */
  function randomString($length, $uc, $n, $sc) {
      $rstr='';
      $source = 'abcdefghijklmnopqrstuvwxyz';
      if ($uc)
          $source .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      if ($n)
          $source .= '1234567890';
      if ($sc)
          $source .= '|@#~$%()=^*+[]{}-_';
      if ($length > 0) {
          $rstr = "";
          $length1= $length-1;
          $input=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')  
          $rand = array_rand($input, 1)
          $source = str_split($source, 1);
          for ($i = 1; $i <= $length1; $i++) {
              $num = mt_rand(1, count($source));
              $rstr1 .= $source[$num - 1];
              $rstr = "{$rand}{$rstr1}";
          }
      }
      return $rstr;
  }
查看更多
够拽才男人
3楼-- · 2019-01-31 03:20

You can try this:

 function KeyGenerator($uid) {
    $tmp = '';
    for($z=0;$z<5;$z++) {
      $tmp .= chr(rand(97,122)) . rand(0,100);
    }
    $tmp .= $uid;
    return $tmp;
  }
查看更多
仙女界的扛把子
4楼-- · 2019-01-31 03:21

I find that base64 encoding is useful for creating random strings, and use this line:

base64_encode(openssl_random_pseudo_bytes(9));

It gives me a random string of 12 positions, with the additional benefit that the randomness is "cryptographically strong".

查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-31 03:23

Creates a 200 char long hexdec string:

$string = bin2hex(openssl_random_pseudo_bytes(100));

maaarghk's answer is better though.

查看更多
ら.Afraid
6楼-- · 2019-01-31 03:28

It really depends on your requirements.

I needed strings to be unique between test runs, but not many other restrictions.

I also needed my string to start with a character, and this was good enough for my purpose.

$mystring = "/a" . microtime(true);

Example output:

a1511953584.0997

查看更多
何必那么认真
7楼-- · 2019-01-31 03:29

How to match the OPs original request in an awful way (expanded for readability):

// [0-9] ASCII DEC 48-57
// [A-Z] ASCII DEC 65-90
// [a-z] ASCII DEC 97-122
// Generate: [A-Za-z][0-9A-Za-z]
$r = implode("", array_merge(array_map(function($a)
                             {
                                 $a = [rand(65, 90), rand(97, 122)];
                                 return chr($a[array_rand($a)]);
                             }, array_fill(0, 1, '.')),
                             array_map(function($a)
                             {
                                 $a = [rand(48, 57), rand(65, 90), rand(97, 122)];
                                 return chr($a[array_rand($a)]);
                             }, array_fill(0, 7, '.'))));

One the last array_fill() would would change the '7' to your length - 1.

For one that does all alpha-nurmeric (And still slow):

// [0-9A-Za-z]
$x = implode("", array_map(function($a)
                           {
                               $a = [rand(48, 57), rand(65, 90), rand(97, 122)];
                               return chr($a[array_rand($a)]);
                           }, array_fill(0, 8, '.')));
查看更多
登录 后发表回答