Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make "uniqid" only give numbers?

Tags:

php

I have the following code which I have put together from different tutorial examples:

<?php

$stamp = date("Ymdhis");
$random_id_length = 6;
$rndid = crypt(uniqid(rand(),1)); 
$rndid = strip_tags(stripslashes($rndid)); 
$rndid = str_replace(".","",$rndid); 
$rndid = strrev(str_replace("/","",$rndid));
$rndid = substr($rndid,0,$random_id_length); 
$orderid = "$stamp-$rndid";
$orderid = str_replace(".", "", "$orderid");
echo($orderid);

?>

FIDDLE: http://phpfiddle.org/main/code/27d-qfw

I would like this to create a number; the current time, followed by a 6 digit random number.

For example: 20130710045730-954762

However at the moment the random digits also include letters.

For example: 20130710045730-Z3sVN2

How can I edit the code to just include numbers? Any help is appreciated.

like image 813
Chris Avatar asked Nov 27 '22 04:11

Chris


1 Answers

uniqid() will already return numbers. But in their hexadecimal representation. In general you could just convert them to decimals:

echo hexdec(uniqid());

The value can only meaningful being observed on a 64 bit system as it is very large and beyond the limits of an 32bit signed integer (like php's one). And that's the point. uniqid() uses such large numbers together with other techniques to ensure a high grade of uniqness. If you are using only 6 digits, you cannot grant this anymore. The risk that values will collide will be high.

I would suggest to generate an application wide uniqness using an auto_increment value in a database or something similar to that.

like image 153
hek2mgl Avatar answered Dec 15 '22 15:12

hek2mgl