Welcome to this tutorial on making a php based calendar. I've split it up into manageable chunks. You can see the type of calendar we're going to make
here. This tutorial will show you how php's date functions work and you'll see "for" loops being used in a real world example.
So let's get started then……php has a many date functions, you can for example use them to find what day of the week it will be exactly 6 months from now and all sorts of similar things. Also in need of a mention is that php can represent each week day numerically....ie. Sunday = 0, Monday = 1, Tuesday = 2, right through to Saturday which is 6. (Why this is important will become clear in just a second). So….from the outset we need to establish to five things…………they are:
What the current month is,
What the current year is,
The numerical value for the weekday falling on the 1st of the month,
The numerical value for the weekday falling on the last day of the month,
The total number of days in the current month.
Let's start with the first two…….date("n") gives us the current month in numerical form... Then date("Y") gives us the current year. Now I actually want to place these two values into session variables….(again you'll see why later)………so at the very top of our page before anything else do the following...
1
2
3
| <?php
session_start( );
?> |
then further down the page…..after the body do this…..
1
2
3
4
| <?php
$_SESSION['month'] = date("n");
$_SESSION['year'] = date("Y");
?> |
then I prefer to place the session variables into normal variables, so do this.
1
2
| $month = $_SESSION['month'];
$year = $_SESSION['year']; |
Ok, So now with the last three on the list I mentioned earlier...you can see that the date( ) and mktime( ) functions can you give you certains specifics.
1
2
3
4
5
6
|
$firstDayNumber = date("w",mktime(0,0,0,$month,1,$year));
$lastDayNumber = date("w", mktime(0,0,0,$month+1,0,$year));
$numberOfDays = date("t",mktime(0,0,0,$month,1,$year));
|
Okay so that's our five things taken care of, below is a snapshot of the code you should have at this stage. If you'd like to take a break and review what we've covered so far that's fine, if you'd ready to carry on just go to page 2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| <?php
session_start();
?>
<html>
<head>
<title>My calendar</title>
</head>
<body>
<?php
$_SESSION['month'] = date("n");
$_SESSION['year'] = date("Y");
$month = $_SESSION['month'];
$year = $_SESSION['year'];
$firstDayNumber = date("w",mktime(0,0,0,$month,1,$year));
$lastDayNumber = date("w", mktime(0,0,0,$month+1,0,$year));
$numberOfDays = date("t",mktime(0,0,0,$month,1,$year));
?> |