Recipe 24.1. Getting and Setting File Timestamps


24.1.1. Problem

You want to know when a file was last accessed or changed, or you want to update a file's access or change time; for example, you want each page on your web site to display when it was last modified.

24.1.2. Solution

The fileatime( ), filemtime( ), and filectime( ) functions return the time of last access, modification, and metadata change of a file, as shown in Example 24-5.

Getting file timestamps

<?php $last_access = fileatime('larry.php'); $last_modification = filemtime('moe.php'); $last_change = filectime('curly.php'); ?>

A file's modification time can be updated with touch( ). Without a second argument, touch( ) sets the modification time to the current date and time. To set a file's modification time to a specific value, pass that value as an epoch timestamp to touch( ) as a second argument. Example 24-6 changes the modification time of two files without changing their contents.

Changing file modification times

<?php touch('shemp.php');          // set modification time to now touch('joe.php',$timestamp); // set modification time to $timestamp ?>

24.1.3. Discussion

The fileatime( ) function returns the last time a file was opened for reading or writing. The filemtime( ) function returns the last time a file's contents were changed. The filectime( ) function returns the last time a file's contents or metadata (such as owner or permissions) were changed. Each function returns the time as an epoch timestamp.

The code in Example 24-7 prints the time a page on your web site was last updated.

Printing web page modification times

<?php print "Last Modified: ".strftime('%c',filemtime($_SERVER['SCRIPT_FILENAME'])); ?>

24.1.4. See Also

Documentation on fileatime( ) at http://www.php.net/fileatime, filemtime( ) at http://www.php.net/filemtime, and filectime( ) at http://www.php.net/filectime.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net