Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the PHP function microtime return an integer even if return as float is set to true?

Tags:

php

A user of my website reported an error the other day so I had a look through the logs and tracked it down. The error was:

Undefined offset: 1

The code in question that caused this error was:

$parts = explode('.', microtime(true));
$nonce = base_convert($parts[1], 10, 36);

So $parts[1] was undefined basically. Could this be because when microtime was called it just so happened that it was an exact second so it returned an int without any decimal places?

like image 501
geoffs3310 Avatar asked Oct 28 '25 13:10

geoffs3310


1 Answers

A quick test can confirm your assumption:

<?php

while (true) {
    $microtime = microtime(true);

    $tmp = explode('.', $microtime, 2);

    if (sizeof($tmp) === 1) {
        var_dump($microtime);
        break;
    }
}

Prints

float(1508171125)

On my system. So yes, microtime can return an "integer".

It makes sense if you think about it, a round number doesn't need the comma separator.

For creating nonce values I suggest using random_bytes() (if you are using PHP7) or openssl_random_pseudo_bytes() which are a lot safer than microtime.

like image 165
marco-a Avatar answered Oct 31 '25 03:10

marco-a



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!