I'm debugging some older PHP code. The original programer included an operation which I think is intended to generate a random id string, by adding two random integers
to a string
and passing it to the md5()
method, which seems to break the program:
$id = md5($someString rand(0, 9999999) rand(0, 9999999));
Passing each part of the argument to the method separately works as expected:
$id = md5($someString); // Works fine
$id = md5(rand(0, 9999999)); // Works fine
Joining the arguments together as a string
before passing it also works:
$randomInt_0 = rand(0, 9999999);
$randomInt_1 = rand(0, 9999999);
$id = md5($someString . $randomInt_0 . $randomInt_1); // Works fine
Why is the original code not working (I assume it did at some point)?
Might passing a string
integer
addition to md5()
cause a problem?
CodePudding user response:
This would have "worked" in PHP<8 by implied conversion from string to integer for $someString
according to the docs.
eg:
"1234"
to1234
"1234foo"
to1234
plus a notice."foo"
to0
plus a warning.
Post PHP8 the second is now a warning, and the third is an error.
You can make this bad code work with an explicit cast:
md5((int)$someString rand(0, 9999999) rand(0, 9999999));
But given the context it would be less incorrect to write it as concatenation instead:
md5($someString . rand(0, 9999999) . rand(0, 9999999));
Since this is probably for some sort of unique token, and preserving the input string as a string and not 0
would put more entropy in the token.