Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

php - PHP随机字符串生成器(PHP random string generator)

I'm trying to create a randomized string in PHP, and I get absolutely no output with this:

(我正在尝试在PHP中创建一个随机字符串,并且我对此绝对没有输出:)

<?php
    function RandomString()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        for ($i = 0; $i < 10; $i++) {
            $randstring = $characters[rand(0, strlen($characters))];
        }
        return $randstring;
    }

    RandomString();
    echo $randstring;

What am I doing wrong?

(我究竟做错了什么?)

  ask by Captain Lightning translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To answer this question specifically, two problems:

(要具体回答这个问题,有两个问题:)

  1. $randstring is not in scope when you echo it.

    (当您回显它时, $randstring不在范围内。)

  2. The characters are not getting concatenated together in the loop.

    (这些字符在循环中没有并置在一起。)

Here's a code snippet with the corrections:

(这是包含更正的代码段:)

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

Output the random string with the call below:

(通过以下调用输出随机字符串:)

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();

Please note that this generates predictable random strings.

(请注意,这会生成可预测的随机字符串。)

If you want to create secure tokens, see this answer .

(如果要创建安全令牌, 请参见此答案)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...