7

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
Chris
  • 431
  • 5
  • 11
  • 18

4 Answers4

34

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.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
5

If it's a random string, use something like this:

$stamp = date("Ymdhis");
$random_id_length = 6;
$rndid = generateRandomString( $random_id_length );

$orderid = $stamp ."-". $rndid;
echo($orderid);

function generateRandomString($length = 10) {
  $characters = '0123456789';
  $randomString = '';
  for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, strlen($characters) - 1)];
  }
  return $randomString;
}

// Output example: 20130710055714-462231

Example: http://codepad.org/eukiOb6S

Fn modified from https://stackoverflow.com/a/4356295/1265817

Community
  • 1
  • 1
DACrosby
  • 11,116
  • 3
  • 39
  • 51
0

Use this code.I think this will be help.

rand(100000,999999)

Enter the two number which digit number do you want

r.vengadesh
  • 1,721
  • 3
  • 20
  • 36
0

Use this:

str_pad(rand(0,'9'.round(microtime(true))),11, "0", STR_PAD_LEFT); 
Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • 3
    Add further explanation of why this will work and why OP wasn't getting it right – NSNoob Jan 28 '16 at 13:02
  • please visit this link for more details [http://php.net/manual/en/function.str-pad.php] . And round(microtime(true)) always calls the microtime.. – Jasveer Singh Jan 29 '16 at 05:27