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?
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.
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.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With