1

I'm debugging some older PHP code. The original programmer 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?

2
  • 3v4l.org/em1rk concatenation in PHP is the . not the + Just like you used in the lines that work :) Commented Jan 18, 2023 at 18:21
  • 2
    @RiggsFolly "concatenating" with + would have "worked" in legacy versions, where a non-numeric string would have been silently coerced to an integer (0). 3v4l.org/vNSol#v5.0.5 ... which is probably not what was intended, but it passed as a meaningless 0 + rand + rand. Commented Jan 18, 2023 at 18:36

1 Answer 1

2

This would have "worked" in PHP<8 by implied conversion from string to integer for $someString according to the docs.

eg:

  • "1234" to 1234
  • "1234foo" to 1234 plus a notice.
  • "foo" to 0 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.