Dynamic websites with PHP (part 3)

Great stuff, now show me the date thing

Making dates dynamic with PHP is even easier than building modular websites with the include function. We're going to do this using the date function (what else would it be called?).

What is the date?

The thing to remember about the PHP date function is that it always returns server time. So, if your server is in the UK, the returned time will be the current time in the UK. This differs from JavaScript time, which always returns the local time because it runs in the client browser. As long as you are aware of this, it's safe to proceed.

Hang on, that could cause complications

Yes, it might but as long as you know what's going on, you can work with it. For example, some applications built on PHP allow the user to set their local timezone. Once this is done, PHP can work out their local time and blog posts etc. can be tagged correctly.

There are many situations where it doesn't really matter. For example, the copyright year in our footer does not need to be switched on the stroke of midnight, as long as it gets updated around that time, that's good enough. The important thing is that we didn't need to do it manually — no one wants to interupt their New Year celebrations to update a copyright notice!

OK, let's do it

Currently, our non-dynamic HTML footer looks like this:

<footer> Copyright &copy; 2013 David Watson. All Rights Reserved. </footer>

The year, “2013” is just static text and will remain unchanged, irrespective of the actual year, unless we change it manually.

Let's replace the year text with a little bit of PHP:

<footer> Copyright &copy; <?php echo date('Y'); ?> David Watson. All Rights Reserved. </footer>

Each time the page is requested, the date function is run, it gets the current date and time from the server in the form of a string of digits and then formats it as requested. In this case, the format string upper-case Y tells the function to return the full, 4-digit year number. The echo function then tells the PHP parser to print the year number as plain text. The server then sends the file out to the client.

It's just like magic

Yes, it is and the whole process is completely hidden from the user. If try to view the source of a PHP file, you won't see any PHP code; you only see the HTML that has been generated.

Can I do other stuff with the date function?

Yes, you can. The date can be formatted in many different ways. For example, this bit of PHP:

<?php echo date('jS F Y H:i:s'); ?>

Will return a date/time that looks something like this:

12th November 2014 10:23:55

How can I find out how the formatting works?

All PHP functions are described in detail on the PHP manual website. The page for the date function includes a description of all the formatting characters — you'll be amazed at the number of options.