Articles: 843 | Categories: 148   
   
   
Home Articles Contact Us
 
 
 
 
Event Calender (0 Comments)
Admin: Posted Date: March 3, 2010

An events calendar allows you to keep a schedule of your appointments, etc. In this article Mitchell creates an extremely useful events calendar using only PHP. We will be using PHP and a flat file to store the events for the calendar.

A Useful Event Calendar Written In PHP

An events calendar allows you to keep a schedule of your appointments, etc. In this article Mitchell creates an extremely useful events calendar using only PHP.I don't want a PDA and I don't want to use the features of my phone to store appointments or my schedule.

I practically live on the web, as I'm sure many of you do. I want a web-based calendar that I have full control of. I want to be able to add and delete my own events and easily know which dates I've set events for. I'm a big PHP fan, so I want to create my own.

I bet you've never really thought about just how important an events calendar is to you. If you don't have an events calendar and you're always trying to remember appointments and your busy business schedule then I'm here to save the day!

Yesterday I decided that instead of buying a Compaq iPAQ, I would sit down and create my own web based events calendar. In this article I'm going to run you step-by-step through the code that I used to create my calendar.

We will be using PHP and a flat file to store the events for the calendar. I know that I could've used a database to store the events, but I wanted to make the calendar as quick and easy to setup as possible. I also wanted as many people to be able to use it as possible.

In this article I will assume that you're using PHP version 4.1 on a Linux web server. If you're not then only minor modifications may be required, however everything should work perfectly 90% of the time.

The event calendars logic


(Page 2 of 6 )

As the name suggests, an events calendar stores events. These events are shown along with the calendar when a specific day is selected, such as the 11th June, 2002. The calendar will display events in a "by month" format, meaning that each of the thirty or so days for a month will be shown on one page. If any of the days have events "attached" to them, then that day will be highlighted in blue. Likewise, today's date will be highlighted in grey, and the currently selected day (if any) will be highlighted in red.

If we click on a day, then all of the events attached to that day will be displayed, along with a form through which we can add a new event. All events include a link to remove them.

So, just to get you excited, here's what the calendar will look like when we're finished:

A sneak preview of our calendar

Today is the 11th, so see how June 11th is highlighted in grey? The PHP code to drive our calendar will be stored in one file called cal.php. Cal.php will work with a flat text file called cal_events.text. Cal_events.text will contain the list of events for our calendar. Each event is stored in the following format:

[Month] [Day] [Year]
[Event Name]
[Event Description]

So if I had an event reminding me that today is the 11th of June, then it would be stored in cal_events.text like this:

06 11 2002
Today is the 11th Of June!
Guess what, today is the 11th of June. Woohoo!

Each entry takes up three rows, and we can use PHP's powerful file and array functions to effortlessly grab each event from the flat file and display/delete it accordingly.

Cal.php is separated into three different sections:
  • Add Post: The AddPost() function allows us to add an event to a specific day of our calendar.
  • Delete Post: The DelPost() function allows us to delete an event from our calendar.
  • Display Calendar: We display the calendar by making use of PHP’s powerful date manipulation functions, by using for loops, and also by opening the events file and flagging particular days that contain events, etc.
Each day in a particular month is represented as part of a table as a <td> cell. The calendar was designed to take advantage of Internet Explorer's Cascading Style Sheet (CSS) abilities, so at the top of cal.php I have defined some styles for various parts of the calendar:

.normal {
font-family: Verdana;
font-size: 8pt;
color: #000000;
height: 20;
padding-left: 5pt;
}

This style is used for normal days. By a normal day I mean a day that isn't today and a day that contains no events.

.today {
font-family: Verdana;
font-size: 8pt;
color: #FFFFFF;
background-color: #CACACA;
height: 20;
padding-left: 5pt;
}


This style is used to highlight the current day, making it easy to work out what the day is and how many days there are until the end of the month, etc.

.selected {
font-family: Verdana;
font-size: 8pt;
color: #FFFFFF;
background-color: #C00000;
height: 20;
padding-left: 5pt;
}


When we click on a day to view its events, this style will highlight it in a bright red, making it stand out from the rest of the days around it.

.event {
font-family: Verdana;
font-size: 8pt;
color: #000000;
background-color: #C6D1DC;
height: 20;
padding-left: 5pt;
}


Lastly we have the event style, which is used for any day that is attached to one/more events from the events file.

After adding a couple of events and selecting a day, here's how our calendar will look:

Our calendar in action

In the screen shot above, days 12, 24 and 28 contain events. It is the 11th of June, so the 11th is highlighted in grey, and we have the 12th day selected, so it is highlighted in red. Note the events for the 12th are shown under the "Today's Events" section just under the calendar.

Well now that we know a bit more about how the calendar functions, let's jump right in and take a look at how to code up the calendar.

Creating the calendar

 

PHP's date functions are excellent, and because they are so powerful it really is a breeze to create a calendar with PHP. Our calendar is flexible in terms of dates. It can either accept a date through the URL by passing in three separate variables, such as:

cal.php?day=3&month=4&year=2004

... which would goto the 3rd of April 2004, or we can just callup cal.php and it will figure out today's date and show the current month on the calendar. Cal.php starts by determining whether or not it has been given a date through the URL or whether it should grab today's date:

// Get values from query string
$day = $_GET["day"];
$month = $_GET["month"];
$year = $_GET["year"];
$sel = $_GET["sel"];
$what = $_GET["what"];

if($day == "")
$day = date("j");

if($month == "")
$month = date("m");

if($year == "")
$year = date("Y");


To move through months and years with the calendar, it passes the date as part of the URL, as we've just seen in the example above.

Once the date has been determined, we use PHP's strtotime function and the date function to get the date as a timestamp as well as the name of the selected month and number of days in that month. We also initialize some variables that we will use later:

$currentTimeStamp = strtotime("$year-$month-$day");
$monthName = date("F", $currentTimeStamp);
$numDays = date("t", $currentTimeStamp);
$counter = 0;
$numEventsThisMonth = 0;
$hasEvent = false;
$todaysEvents = "";


I'm going to skip reading in the events from the events file for now and come back to that a bit later. For now let's concentrate on the PHP code to actually display a basic calendar.

Firstly we setup the table headings, like so:

<table width='350' border='0' cellspacing='0' cellpadding='0'>
<tr>
<td class='head' width='50'>S</td>
<td class='head' width='50'>M</td>
<td class='head' width='50'>T</td>
<td class='head' width='50'>W</td>
<td class='head' width='50'>T</td>
<td class='head' width='50'>F</td>
<td class='head' width='50'>S</td>
</tr>


We setup a variable called $numDays to store the number of days in the current month:

$numDays = date("t", $currentTimeStamp);

We then construct a for loop around this variable to display each day in the month as a table cell. Remember, however, that our table headings for the days of the week start at Sunday and end at Saturday, however each different month could start on a different day, so we have to setup empty cells to push the 1st day of the month under its appropriate day:

for($i = 1; $i < $numDays+1; $i++, $counter++)
{
$timeStamp = strtotime("$year-$month-$i");

if($i == 1)
{
// Workout when the first day of the month is
$firstDay = date("w", $timeStamp);

for($j = 0; $j < $firstDay; $j++, $counter++)
echo "<td>&nbsp;</td>";
}


There are seven days in a week, so each table row contains 7 columns. We use PHP's modulus operator to determine when a new table row needs to begin:

if($counter % 7 == 0)
echo "</tr><tr>";


Once we've setup the empty cells to align the first day of the month with its correct day the we simply fill table cells with the value of $I from the for loop, which represents the day of the month, like so:

echo "<td width='50'>$I</td>";

That's the basics of how to setup a calendar with a HTML table. With the code above however, weekends don't stand out. By adding the following code into the for loop, we highlight the days that fall on either Saturday or Sunday as grey:

if(date("w", $timeStamp) == 0 || date("w", $timeStamp) == 6)
echo "class='weekend'";
else
if($i == date("d") && $month == date("m") && $year == date("Y"))
echo "class='today'";
else
echo "class='normal'";



Getting the "w" attribute of the date returns a numerical value that represents the day of the week. 0 is Sunday and 6 is Saturday, so if the days is a weekend then its CSS class is set to weekend (grey text). If the day is today then its CSS class is set to today (red background). If not, it’s just shown with plain black text and a white background thanks to the "normal" CSS class. The code that we've just looked at would produce a calendar that looked like this:

The calendar with weekends emphasized

We need a way to display the currently selected month and year, as well as a way to navigate from month to month. The solution to this is to setup a form and use two button controls to let us navigate to both the previous and upcoming months:

$monthName = date("F", $currentTimeStamp);

...

<tr>
<td width='50' colspan='1'>
<input type='button' value=' < ' onClick='goLastMonth(<?php echo $month . ", " . $year; ?>)'>
</td>
<td width='250' colspan='5'>
<span class='title'><?php echo $monthName . " " . $year; ?></span><br>
</td>
<td width='50' colspan='1' align='right'>
<input type='button' value=' > ' onClick='goNextMonth(<?php echo $month . ", " . $year; ?>)'>
</td>
</tr>


Notice the two buttons in the code above? They both point to JavaScript functions from their onClick event. The first button calls the goLastMonth function, passing in the selected month and year as parameters. The JavaScript goLastMonth function looks like this:

function goLastMonth(month, year)
{
// If the month is Januaru, decrement the year
if(month == 1)
{
--year;
month = 13;
}

document.location.href = 'cal.php?month='+(month-1)+'&year='+year;
}


Basically all it does it change the URL of our cal.php page, passing in different values for the month and year. GoLastMonth's whole purpose is to take us to the previous month. If we're already in January (month is 1), then we don't want to send the user to month 0, because that wouldn't make sense.

What we do is this: Instead of subtracting from the month, we subtract from the year and set the month to 13. If the month is between 2 and 12, then it's OK to subtract 1 from it, and we do so in the last line of the function:

document.location.href = 'cal.php?month='+(month-1)+'&year='+year;

So as you can see, if we had a month of 1 (January) and a year of 2003, then we would be redirected to the following URL:

cal.php?month=12&year=2002

The goNextMonth JavaScript function works in much the same way, accept it increases the year and resets the month to zero if the current month is December:

function goNextMonth(month, year)
{
// If the month is December, increment the year
if(month == 12)
{
++year;
month = 0;
}

document.location.href = 'cal.php?month='+(month+1)+'&year='+year;
}


Combining this JavaScript and our HTML buttons with the rest of our calendar, when I click the button to proceed from July to August, the code gives us a calendar that now looks like this:

Browsing from July to August

A Useful Event Calendar Written In PHP - Highlighting days with events

As I mentioned earlier, days that have events attached to them are flagged with a blue background thanks to the use of some simple CSS styling. We have a function called ReadEvents that opens the events text file and reads each event into a multi-dimensional associative array. This array is then dissected and checked for events that match each particular day of the month.

ReadEvents accepts one parameter, which is the month to retrieve all events for:

function ReadEvents($Month)
{
// We will get all of the events for this month into an associative
// array and that array will then be returned

$theEvents = array();
$eventCounter = 0;

// Make sure that the file exists
if(!file_exists($_SERVER["DOCUMENT_ROOT"] . "/" . EVENT_FILE))
{
$fp = @fopen($_SERVER["DOCUMENT_ROOT"] . "/" . EVENT_FILE, "w")
or die("<span class='error'>ERROR: Couldn't create events file.</span>");
@fclose($fp);
}

$fp = @fopen($_SERVER["DOCUMENT_ROOT"] . "/" . EVENT_FILE, "rb")
or die("<span class='error'>ERROR: Couldn't open events file to read events.</span>");


We make sure that the events file exists with the use of file_exists. If you receive errors here then make sure that the directory where the event file exists is CHMOD'ed with write attributes.

In the code above we use PHP's DOCUMENT_ROOT server variable to make sure that we have the correct path to the events file. The location of the events file is defined at the top of cal.php as the EVENT_FILE constant and looks like this:

define("EVENT_FILE", "cal_events.text");

You can of course change this to whatever you like. Once we've opened the events file, we use fread to read the contents of the file 1,024 bytes at a time into the $events variable:

while($data = fread($fp, 1024))
{
$events .= $data;
}

@fclose($fp);


Remember that each event has three lines: the date it was posted, a name, and the actual description of the event. We use the explode function to grab all lines separated by the newline character into an array, like so:

// Seperate the data into line-seperated arrays
$arrEvents = explode("\r\n", $events);


Next up we have a for loop. This for loop increments through the $arrEvents array three lines at a time, which means that it only checks the date of each event. It uses the explode function to get the month, day and year of each event into an array called $arrEventDate.

With this array it compares the month that the event was posted to the current month selected on the calendar. If they are the same then that event is added to the $theEvents variable as an associative array, like this:

// Loop through the results and pick the arrays
// that match the selected month
for($i = 0; $i < sizeof($arrEvents); $i+=3)
{
// Get each part of the events date as an index
// of an array
$arrEventDate = explode(" ", $arrEvents[$i]);

// If the month is the selected month the grab
// the details of this event
if((int)$arrEventDate[0] == (int)$Month)
{
$theEvents[$eventCounter++] = array("day" => $arrEventDate[1], "name" => $arrEvents[$i+1], "desc" => $arrEvents[$i+2]);
}
}


Lastly, we return the array:

return $theEvents;

We now have an associative array that contains all events posted for the selected month. We use PHP's foreach construct as well as several if statements to loop through each event and determine which day is was posted for. We then setup the appropriate style for that day's table cell in the calendar table:

foreach($arrEvents as $eventEntry)
{
if($eventEntry["day"] == $i)
{
// We have at least one event for the day
$hasEvent = true;
$numEventsThisMonth++;

}
}
}

// Is it a weekend, does it have events, etc
if($i == $day && $month == date("m") && $year == date("Y") && $sel == 1)
echo "class='selected'";
else if($i == $day && $sel == 1)
echo "class='selected'";
else if($hasEvent == true)
echo "class='event'";
else
if(date("w", $timeStamp) == 0 || date("w", $timeStamp) == 6)
echo "class='weekend'";
else
if($i == date("d") && $month == date("m") && $year == date("Y"))
echo "class='today'";
else
echo "class='normal'";


Browsing by day
OK, we can now show each month on the calendar, but we also need to show each day on the calendar as well as the events attached to each day. To do this, we setup each day of the calendar as a hyperlink. Something like this:

cal.php?sel=1&day=11&month=6&year=2002

The key here is the sel=1 query string variable. We use this to flag that a day is selected and display the events for that day, like so:

$arrEvents = ReadEvents($month);

...

foreach($arrEvents as $eventEntry)
{
if($eventEntry["day"] == $i)
{
// We have at least one event for the day
$hasEvent = true;
$numEventsThisMonth++;

if($eventEntry["day"] == $day)
{
// Add the event to the $todaysEvents variable
$todaysEvents .= "<span class='eventTitle'>" . stripslashes($eventEntry["name"]) . "</span>";

$todaysEvents .= "<span class='eventDesc'><br>" . stripslashes($eventEntry["desc"]) . "</span><br>";

$todaysEvents .= " <a href='cal.php?sel=1&what=delPost&day=$day&month=$month&year=$year&eName=" . urlencode($eventEntry["name"]) . "&eDesc=" . urlencode($eventEntry["desc"]) . "'>[Remove]</a><br><br>";
}
}
}

A Useful Event Calendar Written In PHP - Adding an event


If a particular day is selected, then we also show a form to add a new event to the current day under the list of events. The form is just basic HTML and looks like this:

The form to add a new event

When the new event form is submitted, the AddPost function is called with the selected day, month and year, as well as the name and details of the post:

function AddPost($Day, $Month, $Year, $Name, $Desc)

AddPost simply opens the events file and output the details of the new post, like this:

// Add this event to the events file
$fp = @fopen($_SERVER["DOCUMENT_ROOT"] . "/" . EVENT_FILE, "a")
or die("<span class='error'>ERROR: Couldn't open events file to write event.</span>");

@fputs($fp, "$Month $Day $Year\r\n$Name\r\n$Desc\r\n")
or die("<span class='error'>ERROR: Couldn't write to events file.</span>");

@fclose($fp);


Deleting an event
As you may've noticed in the screenshot above, each event is displayed with a "Remove" link beneath it. This link calls cal.php with the details of the post to be deleted.

The DelPost function handles the deletion of an event, but because we're working with a file, we read all events in and then only write-out the ones that aren't marked for deletion by calling the AddPost function. We do this by comparing the selected event with all events in the events file:

for($i = 0; $i < sizeof($arrEvents); $i+=3)
{
if(!($arrEvents[$i] == $EventDate && $arrEvents[$i+1] == $Name && $arrEvents[$i+2] == $Desc))
{
// This entry hasn't been chosen to be deleted.
// We will add it back to the events
if($arrEvents[$i+1] != "" && $arrEvents[$i+2] != "")
{
// Start by getting the date of the post
$thisDate = explode(" ", $arrEvents[$i]);
AddPost($thisDate[1], $thisDate[0], $thisDate[2], $arrEvents[$i+1], $arrEvents[$i+2]);
}
}
}

A Useful Event Calendar Written In PHP - Conclusion


In this article we've seen how to create our own events calendar that runs using PHP and a flat file to store the details of each event. This calendar is quick to setup and is great if you're always on the move and need to keep track of your appointments, etc.

If you find this calendar useful then be sure to grab the support material using the link below and customise the calendar to meet your needs. If you wanted to, you could modify the code to make it work with a MySQL/Oracle/SQL Server database, have the ability to edit events, etc. The things you can do with this calendar are bound only by time and your imagination. Happy calendering!

 
 
Add a Comment:
 
(You must be signed in to comment on an article. Not a member? Click here to register)
   
Title:

Comments: