Use PHP to insert an automatic “last modified” date into web pages
Use PHP to generate a “Last modified” date into your static web pages that automatically updates when the page does, so you don’t need to worry about it.
When one is presenting factual information within a website, the date that the information was published is of critical importance so that a user can determine the relevance or accuracy of that information. Data or information that was accurate in 2004 may not be so today. Therefore, a “last modified” date is important for information-based websites.
Whilst a web designer can add a “last modified” date manually to a static PHP page, it seems more logical to automate the process so that the date and time are automatically updated when the file is.
The problem with many PHP scripts that utilise the
date() function in PHP to echo the “last modified” date is that one is required to insert the file name manually. This is not efficient nor practical in most situations as the code has to be changed for every page.
Instead, the following code can be used to automatically publish a “last modified” date within any web page:
<?php $file = $_SERVER["SCRIPT_NAME"]; $break = Explode('/', $file); $pfile = $break[count($break) - 1]; //echo $pfile; echo "This page was last modified on " .date("d F Y \at g:ia",filemtime($pfile)); ?>
The output of this code would be in the format “This page was last modified on 30 October 2011 at 2:23pm“.
The first part of this code determines the file name of the page in which it is included, so that the code snippet can be included in any page on your web server.
The format of the
date() output can be easily modified by altering the PHP date string parameters. You will notice that “at” has been uniquely formatted. Both a and t are date string parameters and need to be escaped with a backslash so that they display as “at” and not two more variables.
For some reason, \t does not display as the letter “t” within
date() on my web server (which uses PHP 5.2.17 ) so I have included it as an HTML entity (t) instead. Therefore the word “the” could be included as either \t\h\e or the. The former is obviously the preferred solution. You need only use a backslash to escape characters that are date string parameters. So for instance, you would not need to escape the letter “b”.
To make this task really easy, I suggest that a PHP file be made with the “date modified” code and stored centrally as “date-modified.php” on your server. The file could then be served as a PHP include within individual pages:
Page last modified: <?PHP include("/path/to/date-modified.php");?>
The final aspect to consider is that this code will display when the page was modified, not necessarily the information contained within. So for example, your correction of a small typographical mistake would cause the date to be revised. Therefore, you need to consider whether this meets your requirements or not.