« PHP / MySQL select data and split on pagesPHP validation and verification »

How to make a PHP calendar Posted in PHP Tutorials | 116 Comments

In this tutorial you will learn how to build your own web based calendar using PHP. This calendar is made from two parts. On top there are the links to the previous and the next month, and below them is the calendar itself. It will show the selected month name with the year following and the days of the month bellow in a table view. You will need a good PHP editor to help you with your development or if you are experienced enough you can use a plain text editing software such as Notepad.

At the begining we have to decide how we are going to pass our parameters. We can use either 'hidden' input fields in out html code or pass them in the URL. In this tutorial we will use the second approach. We are going to need two parameters - one for the "month" and one for the "year". We will also need an array with month names:


<?php
$monthNames = Array("January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December");
?>

First we need to check if we have set up our parameters already. If we have not, we set them to the current month and year. (For detailed explanation of date() function please refer to PHP Manual ).
<?php
if (!isset($_REQUEST["month"])) $_REQUEST["month"] = date("n");
if (!isset($_REQUEST["year"])) $_REQUEST["year"] = date("Y");
?>

Lets also set the variables that we are going to use in our calandar:
<?php
$cMonth = $_REQUEST["month"];
$cYear = $_REQUEST["year"];

$prev_year = $cYear;
$next_year = $cYear;
$prev_month = $cMonth-1;
$next_month = $cMonth+1;

if ($prev_month == 0 ) {
$prev_month = 12;
$prev_year = $cYear - 1;
}
if ($next_month == 13 ) {
$next_month = 1;
$next_year = $cYear + 1;
}
?>

$cMonth and $cYear are used for the current month and year displayed on the calendar. For the "Previous" and "Next" links we will need the coresponding parameters. We set $prev_year and $next_year to the current one. Later we may have to change this but for now it is OK. We also have to set parameters for the next and previous months by adding and subtracting 1. Now is the catch. We have to check if our parameter has not gone over or down the limit. Since there are 12 months in a year if our parameter goes to 13 then it means that another year has passed by and we have to set our "month" parameter back to 1 ( January ) and add 1 to our "year" parameter. The other way around is when we go back in time and our "month" parameter goes to 0. Then we have to decrease our "year" parameter by 1 and set the month paramether to 12 ( December ). Now as we set our links for previous and next months we turn to how to build the actual calendar.
We create a table that will hold our calendar and add the links in one row. Then we add a table in a new row that will hold the days. We also include the month name and the year in the first on the new table. But because arrays are zero based, we need to subtract one from the "month" parameter value to get the correct name.
<table width="200">
<tr align="center">
<td bgcolor="#999999" style="color:#FFFFFF">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="50%" align="left">  <a href="<?php echo $_SERVER["PHP_SELF"] . "?month=". $prev_month . "&year=" . $prev_year; ?>" style="color:#FFFFFF">Previous</a></td>
<td width="50%" align="right"><a href="<?php echo $_SERVER["PHP_SELF"] . "?month=". $next_month . "&year=" . $next_year; ?>" style="color:#FFFFFF">Next</a>  </td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center">
<table width="100%" border="0" cellpadding="2" cellspacing="2">
<tr align="center">
<td colspan="7" bgcolor="#999999" style="color:#FFFFFF"><strong><?php echo $monthNames[$cMonth-1].' '.$cYear; ?></strong></td>
</tr>
<tr>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>S</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>M</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>T</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>W</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>T</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>F</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>S</strong></td>
</tr>

Now we have to set the proper dates for our calendar. We have to make integer representation of the date so we can easily operate with it. Then we get the number of days of the selected month and the number representation (0 for Sunday through 6 for Saturday) of the first day of the month. All of these functions are fully explained in PHP Manual. Our loop that is going to print the dates starts at 0, because the days of the week start from 0 (Sunday). It has to loop through the number of days plus the offset of the first day of the month. We have to print new row for each week. We check this by modulus of the number of days in one week 7. If it equals 0 then it is the begining of the week and we print open row tag <tr> and if it is the end of the week 6 we print close tag for this week </tr>. All we need to do is to check if the day that we print is before $startday. In this case we print empty tag. Otherwise we have to print the date. We make it by subtracting the $startday. we have to add one because we don't want our dates to start from 0.
<?php 
$timestamp = mktime(0,0,0,$cMonth,1,$cYear);
$maxday = date("t",$timestamp);
$thismonth = getdate ($timestamp);
$startday = $thismonth['wday'];
for ($i=0; $i<($maxday+$startday); $i++) {
if(($i % 7) == 0 ) echo "<tr>n";
if($i < $startday) echo "<td></td>n";
else echo "<td align='center' valign='middle' height='20px'>". ($i - $startday + 1) . "</td>n";
if(($i % 7) == 6 ) echo "</tr>n";
}
?>

Now we add just the finishing touches of the html and we have finished the calendar.
</table>
</td>
</tr>
</table>

Do you know PHP / HTML / CSS / JS well?

Write tutorial on a topic you are good in and become a trusted PHP jabber! Share your knowledge with thousands of webmasters and we will reward you for your generosity by giving you bonus points which you can use as a voucher to buy any of our commercial products. Read more about our reward program.

116 Replies to "How to make a PHP calendar"

Daniel April 11, 2014 at 3:56 am | Reply

0

Why at the end of the thing can't they show you the code put together?
Sutandra Haldar March 10, 2014 at 3:24 pm | Reply

0

hi,

This is nice tutorial,can you please tell how i can do the week view of this calender
ummi March 4, 2014 at 7:51 am | Reply

0

php event calendar
myphp2you.blogspot.com/2014/03/php-event-calendar_3.html
Aranyos February 25, 2014 at 1:38 pm | Reply

0

Hi, Thank you for this calendar script!

I found a litle complicate the orig date looping.
I made a new one used this skeleton. It gives back the correct day, month and year by php getDate() function.
The calendar can step the day, month and year and highlight the current day. It has a current day button.


First I get the day, month and year data from the request.


if(!isset($_REQUEST['day'])) $_REQUEST['day'] = date('d');
if (!isset($_REQUEST["month"])) $_REQUEST["month"] = date("n");
if (!isset($_REQUEST["year"])) $_REQUEST["year"] = date("Y");


$cDay = $_REQUEST['day'];
$cMonth = $_REQUEST["month"];
$cYear = $_REQUEST["year"];


Second. Made Previous and Next dates of day, month and year


$next_day =getDate(mktime(0,0,0,$cMonth,$cDay+1,$cYear));
$prev_day =getDate(mktime(0,0,0,$cMonth,$cDay-1,$cYear));

$next_month = getDate(mktime(0,0,0,$cMonth+1,$cDay,$cYear));
$prev_month = getDate(mktime(0,0,0,$cMonth-1,$cDay,$cYear));

$next_year = getDate(mktime(0,0,0,$cMonth,$cDay,$cYear+1));
$prev_year =getDate(mktime(0,0,0,$cMonth,$cDay,$cYear-1));



The table skeleton like the orig script with day stepping, current day highlighting and current day button.


<table width="200">
<tr align="center">
<td bgcolor="#999999" style="color:#FFFFFF">
<table width="100%" border="0" cellspacing="0" cellpadding="0">

<!-- Link gombok. Az hónapokat lehet növelni, csökkentni vele. A következő vagy előző hónap számát a linkben küldjük tovább.
A $_SERVER['PHP_SELF'] változó a könyvtárszintümket tárolja. Ehhez tesszük, hozzá lekérdezésként az értékeket.
A link elküldése után visszatérünk ugyanerre a .php scriptre ami rögtön ellenörzi van e valami adat a $_REQUEST[]
tömbben.
-->
<tr>
<td colspan="3" align="left"><a href="<?php echo $_SERVER['PHP_SELF']."?day=". $prev_year['mday'] ."&year=". $prev_year['year'] ."&month=". $prev_year['mon'] ?>" style="color:#ffffff">Previous</a></td>
<td colspan="3" align="left" style="color:blue">Year</td>
<td colspan="3" align="right"><a href="<?php echo $_SERVER['PHP_SELF']."?day=". $next_year['mday'] ."&year=". $next_year['year'] ."&month=". $next_year['mon'] ?>" style="color:#ffffff">Next </td>
</tr>

<tr>
<td colspan="3" align="left"><a href="<?php echo $_SERVER['PHP_SELF']."?day=". $prev_month['mday'] ."&year=". $prev_month['year'] ."&month=". $prev_month['mon'] ?>">Previous </a></td>
<td colspan="3" align="left" style="color:blue">Mounth</td>
<td colspan="3" align="right"><a href="<?php echo $_SERVER['PHP_SELF']."?day=". $next_month['mday'] ."&year=". $next_month['year'] ."&month=". $next_month['mon']; ?>" style="color:#FFFFFF">Next </a> </td>
</tr>

<tr>
<td colspan="3" align="left"><a href="<?php echo $_SERVER['PHP_SELF']."?day=". $prev_day['mday'] ."&year=". $prev_day['year'] ."&month=". $prev_day['mon'] ?>" style="color:#ffffff">Previous</a></td>
<td colspan="3" align="left" style="color:blue">Day</td>
<td colspan="3" align="right"><a href="<?php echo $_SERVER['PHP_SELF']."?day=". $next_day['mday'] ."&year=". $next_day['year'] ."&month=". $next_day['mon'] ?>" style="color:#ffffff">Next</a></td>
</tr>

</table>
</td>
</tr>
<tr>
<td align="center">
<table width="100%" border="0" cellpadding="2" cellspacing="2">
<tr align="center">
<td colspan="7" bgcolor="#999999" style="color:#FFFFFF"><strong><?php echo $monthNames[$cMonth-1].' '.$cYear; ?></strong></td>
</tr>
<tr>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>S</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>M</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>T</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>W</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>T</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>F</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>S</strong></td>
</tr>
<?php

$timestamp = mktime(0,0,0,$cMonth,1,$cYear);
$maxday = date("t",$timestamp); // visszaadja, hogy az adott hónapban mennyi nap van.
$thismonth = getdate ($timestamp); // tömbben visszakapjuk az idő értékeket
$startday = $thismonth['wday']; // 'wday' = day of the week - számban adja vissza a napot. pl. hétfő=1
for ($i=0; $i<($maxday+$startday); $i++) {
if(($i % 7) == 0 ) echo "<tr>";
if($i < $startday) echo "<td></td>";
elseif(($i - $startday + 1) == $cDay){
echo "<td align='center' valign='middle' height='20px' bgcolor='red'>". ($i - $startday + 1) ."</td>";}
else{
echo "<td align='center' valign='middle' height='20px'>". ($i - $startday + 1) ."</td>";}
if(($i % 7) == 6 ) echo "</tr>";
}
?>

</table>
</td>
</tr>
<tr align="center">
<td bgcolor="#999999"><a href="<?php echo $_SERVER["PHP_SELF"];?>" style="color:#FFFFFF">current date</a></td>
</tr>
</table>

eugene February 24, 2014 at 11:16 am | Reply

0

thanks alot for the code,how can i get the current date and maybe give it a color
Jitender February 11, 2014 at 1:49 pm | Reply

0

This is what i was looking for .
I want to use this to my website myhodal.in .
JD February 10, 2014 at 12:44 pm | Reply

0

Is this all just one file, or are these multiple files? :S
Al January 13, 2014 at 9:00 am | Reply

+1

can you add some codes to highlights the current date? I mean put background color on the cell of the current date. thanks for this awesome tutorial!
Thorndy January 23, 2014 at 12:00 pm

0

This is what I did.

Replace this:
else echo "<td align='center' valign='middle' height='20px'>". ($i - $startday + 1) . "</td>n";


With this:
if ( ($i - $startday + 1) == date("j") && ($cMonth-1) == date("F"))
{
echo "<td class='today' align='center' valign='middle' height='20px'>". ($i - $startday + 1) . "</td>";
}
else
{
echo "<td class='hover' align='center' valign='middle' height='20px'>". ($i - $startday + 1) . "</td>";
}


Then just create a css class called today.
faizan January 10, 2014 at 3:38 pm | Reply

+2

upload file code plzz.....!!!!
jdgremsjr January 10, 2014 at 7:08 pm

+2

Why can't you copy and paste like the rest of us. This is a tutorial not a download site.
PK December 3, 2013 at 12:14 pm | Reply

+3

I need to make a calendar where some days are reserved and this is pointed put by red color on that day. Somehow I need add those days every now and then. Can anyone help?


Please be polite and helpful and do not spam or offend others. We promise you will be treated the same way.

Log in your free account or if you still haven't joined our Webmaster Community Reward Program, you can create your free account now.

Posting tip:
if you use code in your comments please put it in these tags [php], [sql], [css], [js]
PHP code example: [php] echo date("Y-m-d"); [/php]

Thank you,
~ PHPJabbers team ~