Generator for random long hex strings in PHP

As of PHP 5.3 with OpenSSL extension:

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

For your example of 100 digits:

$str = getRandomHex(50);

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);

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...


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

where $strlen is length of random hex string.


While this answers OP's question, if what you are looking for is random, then @danorton answer may be a better fit.


Like this:

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

65 is A while 90 is 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:

$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. Or use md5() instead (but I'd stick to sha1()).

EDIT sha1() outputs 40 chars long string, md5() 32 chars long. 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);

Tags:

Php

Generator