OK, this seems to work very well in limited testing. Should be easily adapted to whatever (I have it write the source of an image tag, but it could write the background image of an element):
PHP Code:
<!DOCTYPE html>
<html>
<head>
<title>Random Image Each Midnight</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<img src="
<?php
$path = "../site5/cssimages/scaled/"; // set path to images, include trailing slash
$imgfile = "images.txt"; // set path and filename to file to hold image names and current date, should not initially exist
$eol = PHP_EOL; // end of line reference
$date = date("zY", time()); // the current date as day number in the year, followed by the 4 digit year number
if(file_exists($imgfile)){$datedims = file($imgfile, FILE_IGNORE_NEW_LINES);}
else{$datedims = array();}
if (count($datedims) < 1 or (count($datedims) < 3 and $date !== $datedims[count($datedims) - 1])){ // it's the first time or we're beyond time and only one image is left
$imar = glob("$path{*.jpg, *.gif}", GLOB_BRACE); // grab images as array (include/exclude image patterns if/as desired)
if(count($datedims)){ // if this isn't the first time and the $imgfile hasn't been deleted
if(($key = array_search($datedims[0], $imar)) !== false){ // and the current image is still in the folder
unset($imar[$key]); // do not consider it in the next iteration
}
}
shuffle($imar); // random order for images (once shuffled will continue to be random until used up)
$imar[] = $date; // add the current date to the array for checking later
file_put_contents($imgfile, implode($eol, $imar), LOCK_EX); // save for future use
$datedims = $imar; // use current $imar
}
else if ($date !== $datedims[count($datedims) - 1]){ // there're images left but we're past time
array_shift($datedims); // get rid of the first image listing
array_pop($datedims); // remove old outdated date
$datedims[] = $date; // add the current date to the array for checking later
file_put_contents($imgfile, implode($eol, $datedims), LOCK_EX); // save for future use
}
echo $datedims[0]; // write result (first item now in the $datedims array)
?>
">
</body>
</html>
Let me know if there are any problems or questions.
Notes: Unless you have no possibility of the variables used here ever conflicting with other PHP code you're using or may use, the above PHP code should probably be encapsulated as a function, at which point $c could be used to economize on the usage of
count($datedims)
by setting it to that once $datedims is established, and utilizing it instead of the expression. array_splice() might be better than unset(), but is more cumbersome and the subsequent shuffle() restores sequential numeric keys (at least here), and doesn't (in testing) seem to be an issue, even if it didn't, though further changes might make that an issue. Not sure if LOCK_EX is required or even advisable, but seems to me as it should work out well in this scenario.
Bookmarks