Reputation: 834
I have a PHP file that randomly generates an image from a folder on every refresh. I downloaded it from here (which also has an explanation).
Instead of randomly choosing images, how can I have it change the image hourly? For example, I would like it have the same image for an hour, and then change when that hour is up. Basically, a new image based on some time interval.
Thanks for the help.
Upvotes: 2
Views: 404
Reputation: 22817
Keeping it simple, put 8 different pics in img/
named from 1.jpg
to 8.jpg
, then:
$imagePath = sprintf("img/%s.jpg", (date('G') %8) +1);
24-hour format of an hour without leading zeros.
Now you are sure that you have a different pic every hour, and everybody sees the same.
EDIT: narrow or widen the repetition period adjusting modulo, 24
has a few divisors [1, 2, 3, 4, 6, 8, 12].
Upvotes: 0
Reputation: 2468
Find line
$imageNumber = time() % count($fileList);
And replace it with
$imageNumber = (date(z) * 24 + date(G)) % count($fileList);
That should work for you.
Upvotes: 1
Reputation: 14619
I'd say you need a random oracle function. Basically, it's a random()
function that takes an input and generates a random number, with the guarantee that all calls with the same input will give the same output.
To create the value you pass into the oracle, use something that'll change hourly. I'd use julian_day_number * 24 + hour_number
or something of that variety (just hour_number
isn't good enough, as it'll repeat itself every 24 hours).
Then, whenever your page loads, generate your hour number, pass it through your oracle, and use the result just like you use your random value now. It'll still appear random, and it'll change once an hour.
Hope that helps!
Edit: Random oracles don't need to be fancy - they can be as simple as (stolen blatantly from this answer to a different question):
int getRand(int val)
{
//Not really random, but no one'll know the difference:
return ((val * 1103515245) + 12345) & 0x7fffffff;
}
Upvotes: 0