PHP随机字符串生成器 [英] PHP random string generator

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

问题描述

我正在尝试在PHP中创建一个随机字符串,并且我绝对不会得到任何输出:

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

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

    RandomString();
    echo $randstring;

我在做什么错了?

推荐答案

要专门回答此问题,有两个问题:

To answer this question specifically, two problems:

    回显
  1. $randstring不在范围内.
  2. 这些字符在循环中没有并置在一起.
  1. $randstring is not in scope when you echo it.
  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.

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

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