Okay, so I'm trying to create a backend to a system I've developed in JS/Node; the issue I'm having is that my generateID function can't seem to be replicated in PHP correctly?
The JS function is:
// To make id smaller we get microseconds count from more recent date
var start = Date.UTC(2012, 12, 21, 12, 0, 0, 0) * 1000
// Prefix with number, it reduces chances of collision with variable names
// (helpful if used as property names on objects)
, prefix = String(Math.floor(Math.random() * 10))
// Make it more unique
, postfix = Math.floor(Math.random() * 36).toString(36)
, abs = Math.abs;
module.exports = function (time = now()) {
return prefix + abs(time - start).toString(36) + postfix;
};
The PHP version that I've tried to replace is:
$start = strtotime('2012-12-21 12:00:00');
$prefix = (string)(floor(rand() * 10));
$postfix = base_convert(floor(rand() * 36), 10, 36);
return $prefix.base_convert(abs(time() - $start), 10, 36).$postfix;
The results I'm getting a largely different, with Node I can get ID's such as 31ztgtlke4ga but in the PHP version I'm getting 156094750003e9y5v2zjh700
This will print the sample result.
$start = strtotime('2012-12-21 12:00:00', time());
$prefix = rand(0, 10);
$postfix = base_convert(rand(0, 36), 10, 36);
echo $prefix.base_convert(abs(time() - $start * 1000) * 1000, 10, 36).$postfix;
Javascript random and php rand function is different. Javascript random generates a float value between 0 and 1, though php generates an integer value between min and max which are given as parameters.
Hopes this solution helps you.
By the way there's one mistake you made.
In your js code,
var start = Date.UTC(2012, 12, 21, 12, 0, 0, 0) * 1000
this line is incorrect.
Date.UTC function generates a millisecond-based timestamp which is same as Date.now() function.
You can remove * 1000. In this case you have to remove * 1000 too in the php code.
So php line will be look like this.
echo $prefix.base_convert(abs(time() - $start) * 1000, 10, 36).$postfix;
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