在PHP中生成4到8个字符的随机字符串 [英] Generate random string from 4 to 8 characters in PHP

查看:484
本文介绍了在PHP中生成4到8个字符的随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用PHP生成一个字符串,它需要为 unique need 为4到8个字符

我以为我可以使用crc32哈希,但我不能确定有多少个字符,但确定它是唯一的。另一方面,只创建一个密码生成器将生成重复的字符串,并检查表中每个字符串的值将需要一段时间。



我该怎么做?

谢谢!






也许我可以使用:
$ b

 函数unique_id(){
$ better_token = md5(uniqid(rand(),true));
$ unique_code = substr($ better_token,16);
$ uniqueid = $ unique_code;
返回$ uniqueid;
}

$ id = unique_id();

更改为:

 函数unique_id($ l = 8){
$ better_token = md5(uniqid(rand(),true));
$ rem = strlen($ better_token) - $ l;
$ unique_code = substr($ better_token,0, - $ rem);
$ uniqueid = $ unique_code;
返回$ uniqueid;
}

echo unique_id(4);

你认为我每次都会得到唯一的字符串吗?

解决方案

总之,我认为你会得到一个相当不错的随机值。总有碰撞的机会,但你已经尽全力获得随机值。 uniqid()根据当前时间以微秒为单位返回一个随机值。指定rand()(mt_rand()会更好),第二个参数为uniqid()的true应该使该值更加独特。使用md5()散列值也应该使它非常独特,因为即使生成的两个随机值中的小差异也应该由散列函数放大。 idealmachine是正确的,一个较长的值不太可能有一个碰撞比较短的一个。



你的函数也可以更短,因为md5()将始终返回一个32字符长的字符串。试试这个:

$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $函数unique_id($ l = 8){
return substr(md5(uniqid(mt_rand() ,true)),0,$ l);
}


I need to generate a string using PHP, it need to be unique and need to be from 4 to 8 characters (the value of a variable).

I thought I can use crc32 hash but I can't decide how many characters, but sure it will be unique. In the other hand only create a "password generator" will generate duplicated string and checking the value in the table for each string will take a while.

How can I do that?

Thanks!


Maybe I can use that :

  function unique_id(){
  $better_token = md5(uniqid(rand(), true));
  $unique_code = substr($better_token, 16);
  $uniqueid = $unique_code;
  return $uniqueid;
  }

  $id = unique_id();

Changing to :

  function unique_id($l = 8){
  $better_token = md5(uniqid(rand(), true));
      $rem = strlen($better_token)-$l;
  $unique_code = substr($better_token, 0, -$rem);
  $uniqueid = $unique_code;
  return $uniqueid;
  }

  echo unique_id(4);

Do you think I'll get unique string each time for a goood while?

解决方案

In short, I think you'll get a pretty good random value. There's always the chance of a collision but you've done everything you can to get a random value. uniqid() returns a random value based on the current time in microseconds. Specifying rand() (mt_rand() would be better) and the second argument as true to uniqid() should make the value even more unique. Hashing the value using md5() should also make it pretty unique as even a small difference in two random values generated should be magnified by the hashing function. idealmachine is correct in that a longer value is less likely to have a collision than a shorter one.

Your function could also be shorter since md5() will always return a 32 character long string. Try this:

function unique_id($l = 8) {
    return substr(md5(uniqid(mt_rand(), true)), 0, $l);
}

这篇关于在PHP中生成4到8个字符的随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆