Heim  >  Artikel  >  Backend-Entwicklung  >  如何生成绝对唯一且不容易被猜测的推荐码

如何生成绝对唯一且不容易被猜测的推荐码

WBOY
WBOYOriginal
2016-08-20 09:04:101406Durchsuche

不进去数据库查

回复内容:

不进去数据库查

<code class="php">function makeCode($t) {
  $time = $t.mt_rand(10,99); // 要是觉得不够可以加上线程ID等。
  $ce = $time[9];
  $xy = array();
  $xy[0] = array('A','F','D','X','G','H','K','U','P','Y','W','P');
  $xy[1] = array('R','G','H','P','X','D','Y','U','K','F','S','Z');
  // ... 不重复的序列即可
  $xy[9] = array('S','K','T','U','E','Q','V','G','R','X','C','J');
  $rb = '';
  for ($i = 12;$i--;) {
    $rb .= $xy[$ce][$time[$i]];
  }
  return $rb;
}

makecode(time())</code>

对于绝对唯一来说请使用UUID
比如你使用的是linux系统可以

<code>echo file_get_contents('/proc/sys/kernel/random/uuid');
// 输出: 6c509fc7-328b-4d82-9af8-60c44e7b84b4</code>

得到上面这样一个唯一的字符串以后,你想怎么处理就怎么处理,比如截取你需要的长度。
PHP生成UUID的方式有很多,上面只是简单的使用,也推荐一个类库链接


如果是一般的推荐码其实不需要搞很复杂,除非你有很多的用户量。如果是一般的公司我觉得这样也够用

<code>echo substr(md5(uniqid(mt_rand(1000, 9999), true)), 20);
// 输出:1c7a6db616de </code>

<code>echo bin2hex(openssl_random_pseudo_bytes(16));
// 输出: 5a8a80e06ffe44fd0a6931707a26f0cc</code>

同样,你也可以自由截取

http://hashids.org/

加一个校验码就可以了

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn