PHP touch and filemtime
Restore and verify a file modification time.
A simple example
touch and filemtime
- Start with A practice file and a chosen time
- Do this Set the modification time and read it back
- Result The chosen time, at filesystem precision
Syntax
touch($issue, $stamp)
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpRestore a newsletter publication date
A club restores a newsletter from its backup. The archive uses the publication timestamp to sort issues, so the migration sets a known whole-second time and reads it back before indexing.
<?php
$base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . bin2hex(random_bytes(12));
if (!mkdir($base, 0700)) throw new RuntimeException("Cannot create workspace");
try {
$issue = $base . '/issue';
if (!touch($issue, 1704067200)) throw new RuntimeException('Cannot set time');
clearstatcache(true, $issue);
echo filemtime($issue), PHP_EOL;
} finally {
foreach (['issue'] as $name) {
$path = $base . '/' . $name;
if (is_link($path) || is_file($path)) unlink($path);
elseif (is_dir($path)) rmdir($path);
}
rmdir($base);
}
1704067200
The restored instant is midnight UTC on 1 January 2024, expressed in Unix seconds.
Preserve a concert archive date
The school archives its concert program under the original performance date. After writing the export, set its modification time to noon UTC on the recorded day. Which date does the metadata report back?
Restore a newsletter date
The editor restores the date on a copied issue. After writing the export, set its modification time to noon UTC on the recorded day. Which date does the metadata report back?
What to watch for
Filesystems store different time resolutions. Compare at a supported precision.