简体   繁体   English

PHP随机字符串生成器比预期更随机

[英]PHP random string generator more random than expected

I've been using this to gender a random 12 character string: 我一直在使用这个性别随机12个字符串:

//  lost-in-code.com/programming/php-code/php-random-string-with-numbers-and-letters
$ch = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$%^&(){}[]+=-_/?|*#";
$sc = "";    
for ($p = 0; $p < 12; $p++) {
    $sc .= $ch[mt_rand(0,82)];  // 83 is the strlen of characters
} 

It turns out that it in practice it can include a space in the string. 事实证明,它在实践中可以在字符串中包含空格。 This was not expected! 这不是预期的!

Why would it be? 为什么会这样? Does it treat the underscore as a space? 它是否将下划线视为空间? It's been causing random (and until now, untraceable) bugs. 它导致了随机(并且直到现在,无法追踪)错误。

Thanks. 谢谢。

At a guess (not tested) change the quotes around the $ch string to single quotes. 在猜测(未测试)时,将$ ch字符串周围的引号更改为单引号。 stops the braces from being "evaluated" 阻止大括号被“评估”


Edit: 编辑:

Just to update after some testing - it's NOT converting "as is" - so there's something else in the code that's causing problems. 只是在经过一些测试后更新 - 它不是“按原样”转换 - 所以代码中的其他东西会导致问题。 Just ran it over 100,000 times without spaces. 只跑了100,000次没有空格。

Still put as single quotes to rule that issue out (you may have other variables that are getting evaluated) but that alone is not the issue. 仍然作为单引号来规定该问题(您可能有其他变量正在评估),但仅此一点不是问题。

Danger characters are described here 此处描述危险字符

Your function looks good. 你的功能很好看。 I think that the possible scenario is that you apply some decoding function on the resulting string later in the code. 我认为可能的情况是您在代码中稍后对结果字符串应用一些解码函数。 For example "M0i/%20=3ia5" after urldecode will look like "M0i/ =3ia5". 例如,urldecode之后的“M0i /%20 = 3ia5”将看起来像“M0i / = 3ia5”。

You could end up generating html entities. 你最终可能会生成html实体。 Imagine if your code generated &nbsp or &#160 for example, a space would appear in the string. 想象一下,如果您的代码生成了&nbsp &#160或者&#160 ,例如,字符串中会出现一个空格。

Why not just use: 为什么不使用:

    $length = 12;
    $randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
    echo $randomString;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM