note 45039 deleted from function.mktime by betz
| From: | betz@php.net | Date: | Fri, 05 Nov 2004 01:15:19 +0000 |
| Subject: | note 45039 deleted from function.mktime by betz | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-80112@lists.php.net to get a copy of this message | ||
Note Submitter: bnimon at users dot sourceforge dot net
----
Using the mktime() function enabled us to determine tomorrow's date without having long
algorithms (which we thought we were going to have to do).
The following algorithm shows how randomly choose one line from a file. We specifically used this
choose a random quote for that day. Each day, the first user to view this page after midnight will
have PHP choose the next random quote for that day.
Here is the code for that:
/* Random quote of the day code written by Brandon Nimon */
$filename = "logs/quotes.txt";
// the file that a line will be taken from -- this program segment assumes you have lines of
code in logs/quotes.txt
$lineBreak = "\n"; // (varies depending on OS)
$tomorrow = mktime(0, 0, 0, date("n"), date("j") + 1, date("Y"));
// date("j") + 1 will always work in this situation; if you get day 32, it will just
add a month
$qotdfile = "logs/qotd.list";
// this is the location the Quote Of The Day information will be stored
if(!is_file($qotdfile)){
// if the file does not exist, make it (this will only happen once)
$fp = fopen($qotdfile, "w");
// fopen file for editing with pointer at top
$fout = fwrite($fp, $tomorrow . $lineBreak . mt_rand(0, count($quotes) - 1));
// write the information
fclose($fp);
// close out of the file
} // if(!is_file($qotdfile))
if(is_file($qotdfile)){
// this should alway be true, unless permissions are set incorrectly
$array_of_file = file($qotdfile);
// stores each line of the file to an array element
if(trim($array_of_file[0]) > time()){
// if tomorrow has not yet arrived, just display today's date (trim() to make sure there
is no bagage)
echo stripslashes(htmlspecialchars($quotes[trim($array_of_file[1])]));
// the stripslashes() is so that on server that do not have magic quotes enabled there
won't be any \ before the quotes
// and the htmlspecialchars() is so that what was entered will be displayed, not how HTML
translates it to be
} else {
// if this is the first user to view the page after midnight, determine a new random quote of
the day
$rndnum = mt_rand(0, sizeof($quotes) - 1);
// determine the random quote for that day
$fp = fopen($qotdfile, "w");
// fopen file for editing with pointer at top to overwrite anything that might have been
there before
$fout = fwrite($fp, $tomorrow . $lineBreak . $rndnum);
// write the new information
fclose($fp); // close the file
echo stripslashes(htmlspecialchars($quotes[$rndnum]));
// display today's quote
} // if(trim($array_of_file[0]) <= time())
} // if(is_file($qotdfile))
This code is copyrighted, but is under the GNU public license, so it can be redistributed and edited
as you wish.