Search code examples
phpgenerator

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. All these strings have to be same length.

How can I generate random hex strings?


Solution

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