This code is for when you have a list of events
you would like to put on a Web page but don't want to have to keep
track of which events have expired and manually delete them.
Calendar of Events Listing
This code is for when you have a list of events you would like to put on a Web page but don't want
to have to keep track of which events have expired and manually delete them. The code will check
the date of each event and only display the events that are of the current day or forward. Even if
you don't have use for this particular script, you will see how you can use the date format to compare
today's date to other dates.
Let's get into the code:
<?php
$date = date("Ymd");
?>
It's suggested that you use <?php as opposed to <? to start your scripts to avoid any possibility of
confusion with other languages like XML that may use <? by itself. This way there is no question as to
what type of language the server should use to parse the script.
Today's date is looked up using the date function and is put into the $date variable in YYYYMMDD format.
You'll see why in a minute.
<?php
$handle=opendir('events');
?>
Open the events directory.
<?php
while (($file = readdir($handle))!==false) {
if ($file >= $date) {
include("events/$file");
}
}
closedir($handle);
?>
This snippet uses the readdir function which returns the filename of the next file in the directory.
As long as it doesn't return false (!==false means not false), there is another file in the list and it will keep looping through the
while loop. When there isn't another file left to look at, readdir will return false and the while loop will stop.
Note: the PHP manual says that readdir will return the files in no particular order so there is no guarantee that
they will be displayed in chronological order. However, I haven't found this to be a problem. Be sure to check the output so
you know what you're getting.
Each file in the events directory is a plain text file containing the information for each event. Each
file is given a name with the event's date, or the last date of the event in YYYYMMDD format with no file extension. So if
today's date is
March 30, 2010
the YYYYMMDD format filename for an event occurring today would
be 20100330. By using the date in this format, any date that occurred before today
will be less than today's date when compared numerically. Only filenames with the date equal to or greater than today's
date will be displayed.
|