简体   繁体   English

PHP中随机长十六进制字符串的生成器

[英]Generator for random long hex strings in PHP

I have written a generator of strings, but I don't know how to create a random hex string with length, for instance 100 digits, for inserting into a database.我已经编写了一个字符串生成器,但我不知道如何创建一个长度为 100 位的随机十六进制字符串以插入数据库。 All these strings have to be same length.所有这些字符串必须具有相同的长度。

How can I generate random hex strings?如何生成随机十六进制字符串?

As of PHP 5.3 with OpenSSL extension:从带有 OpenSSL 扩展的 PHP 5.3 开始:

function getRandomHex($num_bytes=4) {
  return bin2hex(openssl_random_pseudo_bytes($num_bytes));
}

For your example of 100 digits:对于您的 100 位数字示例:

$str = getRandomHex(50);

While this answers OP's question, if what you are looking for is random , then @danorton answer may be a better fit.虽然这回答了 OP 的问题,但如果您正在寻找的是random ,那么 @danorton 的答案可能更合适。


Like this:像这样:

$val = '';
for( $i=0; $i<100; $i++ ) {
   $val .= chr(rand(65, 90));
}

65 is A while 90 is Z . 65 是A而 90 是Z if you do not like "magic numbers" this form may be more readable:如果您不喜欢“幻数”,则此表格可能更具可读性:

$val = '';
for( $i=0; $i<100; $i++ ) {
   $val .= chr(rand(ord('A'), ord('Z')));
}

I'd make ord() result a variable and move it out of the loop though for performance reasons:出于性能原因,我会将ord()结果设置为变量并将其移出循环:

$A = ord('A');
$Z = ord('Z');
$val = '';
for( $i=0; $i<100; $i++ ) {
   $val .= chr(rand($A, $Z));
}

Or you could glue output of sha1() s (three of them) and cut down to 100 chars.或者您可以粘合sha1()的输出(其中三个)并减少到 100 个字符。 Or use md5() instead (but I'd stick to sha1() ).或者使用md5()代替(但我会坚持使用sha1() )。

EDIT sha1() outputs 40 chars long string, md5() 32 chars long.编辑sha1()输出 40 个字符长的字符串, md5() 32 个字符长。 So if you do not want to glue char by char (as in loop I gave above) try this function因此,如果您不想按字符粘合字符(如我在上面给出的循环中),请尝试使用此功能

function getId($val_length) {
    $result = '';
    $module_length = 40;   // we use sha1, so module is 40 chars
    $steps = round(($val_length/$module_length) + 0.5);

    for( $i=0; $i<$steps; $i++ ) {
      $result .= sha1(uniqid() . md5(rand());
    }

    return substr($result, 0, $val_length);
}

where function argument is length of string to be returned.其中函数参数是要返回的字符串的长度。 Call it getId(100); getId(100);

$randHexStr = implode( array_map( function() { return dechex( mt_rand( 0, 15 ) ); }, array_fill( 0, $strlen, null ) ) );

其中 $strlen 是随机十六进制字符串的长度。

liner technique to do so, but its bit complicated and hard-coded in-terms of length of string.衬里技术这样做,但就字符串长度而言,它有点复杂和硬编码。

$rand4 = substr(sha1(rand(0,getrandmax())),rand(0,24),16); $rand4 = substr(sha1(rand(0,getrandmax())),rand(0,24),16);

in which you need to change the last varibale of function (which i set to 16) if you want to change the length of output string and one more thing there is one rand(0,24) in which number 24 will change according to third variable, it should not be more then 40-thirdvariable...如果要更改输出字符串的长度,则需要更改函数的最后一个变量(我设置为 16),另外还有一个 rand(0,24),其中数字 24 将根据第三个更改变量,它不应该超过 40-thirdvariable...

I like to a have single general function that can handle similar situations.我喜欢有一个可以处理类似情况的通用功能。 By that I mean a function which receives both the requried length of the generated string and the possible characters that can occure in it.我的意思是一个函数,它接收生成的字符串的所需长度和其中可能出现的字符。

That way a single function can create: 40-digit decimal number, 16-digit uppercase hex number, 100 letter lowercase string, etc...这样一个函数就可以创建:40位十进制数、16位大写十六进制数、100个字母小写字符串等...

Here is my implementation:这是我的实现:

/**
 * Generate a random string.
 *
 * @param int    $length Length of the generated string.
 * @param string $chars  The string containing all of the available characters.
 *
 * @return string The generated string.
 */
function getRandomString($length = 10, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
    $str = '';

    $size = strlen($chars);
    for ($i = 0; $i < $length; $i++) {
        $str .= $chars[mt_rand(0, $size - 1)];
    }

    return $str;
}

IMPORTANT: Do not use this function to generate random string for any security purpose.重要提示:请勿出于任何安全目的使用此函数生成随机字符串。 For a secure string generator check out the answer from @danorton.对于安全的字符串生成器,请查看@danorton 的答案。

From php7 on you should use the function random_bytes :从 php7 开始,您应该使用函数random_bytes

function getRandomHex($num_bytes=4) {
  return bin2hex(random_bytes($num_bytes));
}

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

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