php 如何在 Laravel 5 中创建唯一的随机字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33304930/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:26:55  来源:igfitidea点击:

How can I create a unique random string in laravel 5

phprandomlaravel-5

提问by Fokwa Best

I am new to laravel 5. I am working on a project where I want to assign some random-readable uniquestring to each application. I have knowledge of the each application id which may be use as a seed. Since the app is going to be use within the company I don't worry much about security. I expect the table size to grow so my goal is to achieve uniqueness as much as possible because the field in DB is unique. A code like (EN1A20, EN12ZOV etc). If the function can allow me to pass the length of the string I want to return, that would be really awesome.

我是 laravel 5 的新手。我正在做一个项目,我想为每个应用程序分配一些随机可读的唯一字符串。我知道可以用作种子的每个应用程序 ID。由于该应用程序将在公司内使用,因此我不太担心安全性。我希望表大小会增长,因此我的目标是尽可能实现唯一性,因为 DB 中的字段是唯一的。类似(EN1A20、EN12ZOV 等)的代码。如果该函数可以让我传递我想返回的字符串的长度,那就太棒了。

EditShown below is my attempt to the problem

编辑下面显示的是我对问题的尝试

private function generate_app_code($application_id) { 
        $token = $this->getToken(6, $application_id);
        $code = 'EN'. $token . substr(strftime("%Y", time()),2);

        return $code;
    }

    private function getToken($length, $seed){    
        $token = "";
        $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $codeAlphabet.= "0123456789";

        mt_srand($seed);      // Call once. Good since $application_id is unique.

        for($i=0;$i<$length;$i++){
            $token .= $codeAlphabet[mt_rand(0,strlen($codeAlphabet)-1)];
        }
        return $token;
    }

Can the code above do the trick?

上面的代码可以解决问题吗?

Edit

编辑

Actually I borrowed ideas from this post PHP: How to generate a random, unique, alphanumeric string?to come out with the methods above but the post does not entirely address my issues. My goal is to generate a string of length say 6 to 8 (Alphanumeric and readable). This string would be use by my admin for query purposes. In my function I have mt_srand($seed) to seed the random number generator where seed is my application_id. It is possible to get duplicate $token.

实际上我从这篇文章PHP: How to generate a random, unique, alphanumeric string? 中借鉴了一些想法提出上述方法,但该帖子并未完全解决我的问题。我的目标是生成一个长度为 6 到 8(字母数字和可读)的字符串。此字符串将由我的管理员用于查询目的。在我的函数中,我有 mt_srand($seed) 来播种随机数生成器,其中种子是我的 application_id。有可能获得重复的 $token。

Appreciate help.

感谢帮助。

采纳答案by user2094178

With your attempt to the problem you could apply the following to ensure a unique code:

在您尝试解决问题时,您可以应用以下内容来确保唯一的代码:

do
{
    $token = $this->getToken(6, $application_id);
    $code = 'EN'. $token . substr(strftime("%Y", time()),2);
    $user_code = User::where('user_code', $code)->get();
}
while(!empty($user_code));

Edit

编辑

To avoid an infinite loop in laravel, use

为了避免 Laravel 中的无限循环,请使用

do
    {
        $token = $this->getToken(6, $application_id);
        $code = 'EN'. $token . substr(strftime("%Y", time()),2);
        $user_code = User::where('user_code', $code)->get();
    }
    while(!$user_code->isEmpty());

http://laravel.com/api/5.0/Illuminate/Support/Collection.html#method_isEmpty

http://laravel.com/api/5.0/Illuminate/Support/Collection.html#method_isEmpty

or go with

或者一起去

  do
        {
            $token = $this->getToken(6, $application_id);
            $code = 'EN'. $token . substr(strftime("%Y", time()),2);
            $user_code = User::where('user_code', $code)->first();
        }
        while(!empty($user_code));

Instead of get(), use first(). $user_code is probably unique so we can conveniently pull out the first result.

使用 first() 代替 get()。$user_code 可能是唯一的,因此我们可以方便地提取第一个结果。

回答by fico7489

You can use :

您可以使用 :

sha1(time())

Explanation: sha1 is hash function, and most important characteristic of hash function is that they never produce the same hash of different string, so as time() is always unique in theory sha1(time()) will always give you unique string with fixed width.

说明:sha1 是散列函数,散列函数最重要的特性是它们从不产生不同字符串的相同散列,因此理论上 time() 总是唯一的 sha1(time()) 总是会给你唯一的字符串,固定宽度。

EDITED:

编辑:

You can use you function but before giving token you can connect to database and check if token exists, if exists generate new token, if not exists give hin this token. This mechanism will give you unique tokens.

您可以使用您的功能,但在提供令牌之前,您可以连接到数据库并检查令牌是否存在,如果存在则生成新令牌,如果不存在则提供此令牌。这种机制将为您提供独特的令牌。

回答by Flyingearl

You could use the built in helper function:

您可以使用内置的辅助函数:

str_random(int);

The documentation can be found: Laravel 5.1 Docs

可以找到文档Laravel 5.1 Docs

To ensure it is unique you could always check that the name doesn't already exist and if it does rerun the function to generate a new string.

为确保它是唯一的,您可以始终检查名称是否已存在,以及是否确实重新运行该函数以生成新字符串。

Hope that helps.

希望有帮助。