tags:

views:

128

answers:

4

I want to generate a number that contains 14 digits. But I want to generate it in a certain pattern. Consider the following number:

292 0505 150 0253

  • The bold numbers are constants
  • 0505 is a day and a month meaning 05 is the month and 05 is the day. So when generating the random number the first part must be from 0 to 12 and the second one from 1 to 31
  • The other number (150) is random

I want each attempt post to a page by curl.

+2  A: 

Now, if I understood correctly what you want, try this:

$numberAsString = '292' . mt_rand(1, 12) . mt_rand(1, 31) . mt_rand(0, 9) . mt_rand(0, 9) . mt_rand(0, 9) . '0253';

I saved the number as a string because I don't think PHP may handle numbers that large without using floats.

nikic
I think the 292 and 0253 are also supposed to be random
glowcoder
Wasn't sure about that. But the op says 'the bold is the constant number'. So I did these parts constant ;)
nikic
know i want to try to post to a page by curl
moustafa
If the OP really needs valid dates for the first 4 numbers, then this will not be guaranteed to work as it can produce invalid dates.
sberry2A
+1  A: 
function randomNumber($startDate,$endDate){
    $days = round((strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24));
    $n = rand(0,$days);
    return '292'.date("md",strtotime("$startDate + $n days")).rand(100,999).'0253';   
}

$myRandomNumber = randomNumber('2010-01-01', '2010-12-31');
$url = "http://www.example.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $myRandomNumber);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

This is assuming you are POSTing the data. If using GET (or another HTTP method) then changes will be needed.

You can give a date range you want to include for the first 4 random numbers (for example to allow for including / excluding leap years - or to keep the date before today)

sberry2A
+1  A: 

If I understand you correctly:

positions 1-4 random 0000-9999

positions 5,6 (starting with the rightmost) random 01-12

positions 7,8 range 01-31

positions 9-14 random 000000-999999

I dont know whats you backend, but php format is rand (min,max)

You can merge numbers as 14-character-long string, using sprintf on positions 5,6 and 7,8 to ensure leading zero for single-digit date.

32-bit php will not support 14-decimal digits in either int or float. But it does not look like you need to do any math operations on this long number.

selytch
A: 

Convolution & confusion all around.

echo '292'
  .DateTime::createFromFormat('z',rand(0,365))->format('md')
  .sprintf('%03d',rand(0,999))
  .'0253';

Which has the added advantage of not throwing the 000-099 randomness away as the accepted answer does.

Wrikken