Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP generate a random number using todays date

I am trying to assign a block of content (on a webpage) a randomly generated number that is based between todays date (whatever that will be) and a fixed number. For some reason there is dramatic difference in the sorts of numbers being outputted. For example when I test my code locally the numbers generated are good enough for me (in the positive) but when on an actual live server they are generally the opposite and are negative numbers.

This is my one liner:

<?php $today=date('YmdHi'); echo rand(201203140906, $today); ?>

Basically '201203140906' is the Year, Month, Day, Hour.

Is this good or bad? Are there better ways to do this?

like image 445
egr103 Avatar asked Mar 29 '26 16:03

egr103


2 Answers

On a 32-bit system, the largest value that can be held in an INT is 2147483647.

http://php.net/manual/en/language.types.integer.php

If your local machine is 64 bit and your server is 32 bit, they will have different size limits. The server will not be able to handle an integer as large as 201203140906.

You may be able to randomly generate a smaller number and then add that to 201203140906.

Like this perhaps:

$today = date('YmdHi');
$startDate = date('YmdHi', strtotime('2012-03-14 09:06:00'));
$range = $today - $startDate;
$rand = rand(0, $range);
echo "$rand and " . ($startDate + $rand);

OR you can do this to generate a random date in the last ten days:

$today = date('YmdHi');
$startDate = date('YmdHi', strtotime('-10 days'));
$range = $today - $startDate;
$rand = rand(0, $range);
echo "$rand and " . ($startDate + $rand);
like image 86
Scott Saunders Avatar answered Apr 02 '26 15:04

Scott Saunders


<?php 
$then = strtotime('2012-03-14 09:06:00'); 
$now = time();
for($i=0; $i<100; $i++) echo date('YmdHi', rand($then, $now)), '<br>'; 
?>

By the way... you could also be using "uniqid()"

like image 45
Tiago Relvao Avatar answered Apr 02 '26 17:04

Tiago Relvao



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!