PHP generate a random number using todays date

16,337

Solution 1

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);

Solution 2

<?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()"

Share:
16,337
egr103
Author by

egr103

Updated on July 16, 2022

Comments

  • egr103
    egr103 almost 2 years

    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?