The simplest way to create a calendar in a web page is using a table. The difficult part is in entering all the dates into the correct places in the table so as to create the calendar you require for the correct month and year. Well with a simple PHP function we can do away with all the complexity and have the table automatically generated with the correct days filled in in the correct positions in the table for whichever month it is we are trying to create.
The following function accepts two parameters containing the month any year you want to generate the calendar for and it returns the HTML for the entire table containing the calendar for that month. This makes it as flexible as possible as to how we can use the function. Note that the function does not contain any validation for the month and year fields passed to it so you'll need to ensure that the values passed are valid and add any necessary validation if you are going to allow the values to be entered via a form.
You may use this function provided that you leave the copyright notice intact.
To get the calendar looking reasonable we need to style the table to make it look like a calendar. The following is the CSS I used to style my example calendar which you can see at the bottom of this page.
There are a couple of different ways you can use this calendar function. The first way is to dynamically generate a calendar within the web page itself. To do this we simply echo the value returned from the function call as part of our page content. For example the sample calendar at the bottom of the page simply calls the function as follows:
This generates a calendar for the current month and year (and since the parameters are being returned from date functions we do not have a need to validate the values since they must always be valid). You can of course generate a calendar for any month of any year by passing the appropriate month and year values after validating them.
The other use for the function is in generating the HTML for the calendar in a way that can be made available for people to copy to use in web pages elsewhere. That just requires that the calendar function call be wrapped inside two other standard PHP function calls so as to display the HTML code for the calendar rather than displaying the calendar itself.
Here's what the in page calendar looks like for the current month.
And here's what the HTML generated by the function looks like that could be copied to create basis for static calendar pages where you can manually add other information into your calendar. (note that as I am displaying it in a limited width those lines not starting with a <tr> tag have actually wrapped from the preceding line - not that the wrapping would affect the use of the code in any way).