-
Build a simple monthly calendar using PHP
Please follow below 5 steps to create monthly calendar using PHP.
1. Define the current date OR a date coming by POST after the calendar form gets submitted:
View Code PHP1 2 3 4
$today=getdate(); $year=$_POST['year']?$_POST['year']:$today['year']; $month=$_POST['month']?$_POST['month']:$today['month']; $day=$_POST['day']?$_POST['day']:$event['day'];
PHP getdate() function wiil return an array of year, month and day. We assign this to $today variable and will use it to define the calendar day, year and month – if they are coming from POST, the POST values have priority – otherwise we use $today values.
2. Now, define the number of days in the given month. We use function cal_days_in_month() for that:
View Code PHP1
$numdays=cal_days_in_month(CAL_GREGORIAN, $month, $year);
3. Now there’s one specific. Make sure the calendar looks like the printed calendars by defining the week start day.
View Code PHP1 2 3 4
// calculate 'extra' days - these which need to come on the first // line - like 30-31- -- - -- - -- - -- - 1 $estart=(7-$wday)+28; $extra=$numdays-$estart;
Include the design template:
View Code PHP1 2
require_once("mc_template.html");
4. Display year and month drop boxes:
View Code PHP1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<select name="year" onchange="this.form.submit();"> <?php for($i=$start_year;$i<=2050;$i++) { if($i==$year) $selected='selected'; else $selected=''; echo "<option $selected value=$i>$i</option>"; } ?> </select> <select name="month" onchange="this.form.submit();"> <php for($i=1;$i<=12;$i++) { if($i==$month) $selected='selected'; else $selected=''; echo "<option $selected value=$i>".$lmonths[$months[$i]]."</option>"; } // end PHP </select>
5. HTML code:
View Code PHP1 2 3 4 5 6 7 8 9
<?php if($extra<0) $extra=0; for($i=$estart;$i<$numdays;$i++) { // ... // the full code can be downloaded at the bottom } ?>