Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generator for random long hex strings in PHP

Tags:

generator

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?

like image 783
forgatn Avatar asked Nov 18 '12 12:11

forgatn


People also ask

How to generate random characters in PHP?

Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter.

How do you generate random unique alphanumeric strings in laravel?

If you need to generate unique random string then you can use str_random() helper of Laravel. It is very simple and you can use easily. you can easily generate random string in laravel 6, laravel 7, laravel 8 and laravel 9 version using str helper.

How do you generate a random hexadecimal in Java?

To generate Random Hexadecimal Bytes, first, a random byte can be generated in decimal form using Java. util. Random. nextInt() and then it can be converted to hexadecimal form using Integer.


2 Answers

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);
like image 87
danorton Avatar answered Sep 18 '22 16:09

danorton


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

like image 26
Marcin Orlowski Avatar answered Sep 19 '22 16:09

Marcin Orlowski