如何在 PHP 中制作简短的随机唯一键,例如 YouTube 视频 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3990820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make short random unique keys, like YouTube video IDs, in PHP?
提问by kusanagi
Is there any way to create unique keys like those used in YouTube video urls (ex: https://www.youtube.com/watch?v=nWChTnkVdKE)?
有什么方法可以创建像 YouTube 视频网址中使用的唯一键(例如:https://www.youtube.com/watch?v=nWChTnkVdKE)?
采纳答案by Diantre
The idea is to convert a unique integer (such as current time) in an other mathematical base.
这个想法是在其他数学基础上转换一个唯一的整数(例如当前时间)。
A very simple way in PHP :
PHP 中一个非常简单的方法:
// With this precision (microsecond) ID will looks like '2di2adajgq6h'
$id = base_convert(microtime(false), 10, 36);
// With less precision (second) ID will looks like 'niu7pj'
$id = base_convert(time(), 10, 36);
回答by Junaid Atari
A small PHP class to generate YouTube-like hashes from one or many numbers. Use hashids when you do not want to expose your database ids to the user.
一个小的 PHP 类,用于从一个或多个数字生成类似 YouTube 的哈希。当您不想向用户公开数据库 ID 时,请使用 hashhids。
回答by MT.
Use whichever you like :-)
使用任何你喜欢的:-)
// Generates Alphanumeric Output
// 生成字母数字输出
function generateRandomID() {
// http://mohnish.in
$required_length = 11;
$limit_one = rand();
$limit_two = rand();
$randomID = substr(uniqid(sha1(crypt(md5(rand(min($limit_one, $limit_two), max($limit_one, $limit_two)))))), 0, $required_length);
return $randomID;
}
// Generates only alphabetic output
// 只生成字母输出
function anotherRandomIDGenerator() {
// Copyright: http://snippets.dzone.com/posts/show/3123
$len = 8;
$base='ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz';
$max=strlen($base)-1;
$activatecode='';
mt_srand((double)microtime()*1000000);
while (strlen($activatecode)<$len+1)
$activatecode.=$base{mt_rand(0,$max)};
return $activatecode;
}
回答by Gordon
See Sean Coates' Blog:
见肖恩·科茨的博客:
I wanted the URL shortener to make the shortest possible URLs. To keep the number of characters in a URL short, I had to increase the set of characters that could comprise a key.
我希望 URL 缩短器能够生成尽可能短的 URL。为了使 URL 中的字符数保持简短,我不得不增加可以构成键的字符集。
and also the article linked within:
以及链接到的文章:
On a sidenote, this has likely been answered before
在旁注中,这可能之前已经回答过
回答by Bhaskar Bhatt
Here is a small function that generates unique key randomly each time. It has very fewer chances to repeat same unique ID.
这是一个每次随机生成唯一密钥的小函数。重复相同的唯一 ID 的机会非常少。
function uniqueKey($limit = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < $limit; $i++) {
$randstring .= $characters[rand(0, strlen($characters))];
}
return $randstring;
}
source: http://guruquest.net/question/how-to-generate-random-unique-ids-like-youtube-or-tinyurl-in-php/
来源:http: //guruquest.net/question/how-to-generate-random-unique-ids-like-youtube-or-tinyurl-in-php/
回答by Darren
all the methods above are good but make sure you knowand not assume the generated string is unique. What I have done in the past is made a recursive function that checks the string against my database and if it is unique it returns the value, otherwise it just runs again. This will hardly happen though depending how long your unique string is. Its just good to knowits unique.
以上所有方法都很好,但请确保您知道而不是假设生成的字符串是唯一的。我过去所做的是一个递归函数,它根据我的数据库检查字符串,如果它是唯一的,则返回该值,否则它会再次运行。尽管这取决于您的唯一字符串的长度,但这几乎不会发生。很高兴知道它的独特性。
回答by Chetan
From comments on here:
从这里的评论:
<?php
function generateRandStr($length){
$randstr = "";
for($i=0; $i<$length; $i++){
$randnum = mt_rand(0,61);
if($randnum < 10){
$randstr .= chr($randnum+48);
}else if($randnum < 36){
$randstr .= chr($randnum+55);
}else{
$randstr .= chr($randnum+61);
}
}
return $randstr;
}
?>
Simply use:
generateRandStr(10);
Sample output: $%29zon(4f
You can mess around with this function to generate just alphanumeric, or just alphabetic characters.
您可以使用此函数来生成仅字母数字或字母字符。
回答by Wrikken
回答by madhushankarox
<?php
function keygen(){
$chars = "bcdfghjklmnpqrstvwxyz";
$chars .= "BCDFGHJKLMNPQRSTVWXYZ";
$chars .= "0123456789";
while(1){
$key = '';
srand((double)microtime()*1000000);
for($i = 0; $i < 10; $i++){
$key .= substr($chars,(rand()%(strlen($chars))), 1);
}
break;
}
return $key;
}
//echo keygen();
?>
回答by cbmtrx
I was looking for a very quick and simple solution (that was NOT intended to be secure in any way) that would replicate the actual hash code upon regeneration (unlike PHP's microtime unique id). This one did the trick.
我正在寻找一个非常快速和简单的解决方案(这并不打算以任何方式安全),它会在重新生成时复制实际的哈希码(与 PHP 的微时间唯一 ID 不同)。这个成功了。
http://php.net/manual/en/book.hash.php
http://php.net/manual/en/book.hash.php
So:
所以:
for($i=0;$i<count($myArray);$i++) {
$hashCode = "#".hash('crc32b', $myArray[$i]."-".$i);
}
Yields:
产量:
#179507fa
#8e9c5640
#f99b66d6
#67fff375
#10f8c3e3
etc
等等
I won't pretend to know how all the different hash algorithms are used but for non-secure uses (like link #anchors) this is handy.
我不会假装知道所有不同的哈希算法是如何使用的,但对于非安全用途(如链接#anchors),这很方便。