How to Retrieve and Use File Last Access Time with PHP's fileatime()
This article explains the PHP fileatime() function, its syntax, parameters, and return value, and provides practical examples for retrieving a file's last access timestamp, formatting it, and using it for file management tasks such as cleanup based on inactivity.
In PHP, the
fileatime()function retrieves the last access time of a file, i.e., the time it was last read via
readfile()or
fread().
<code>int fileatime ( string $filename )</code>Parameter description:
filename (required): the path of the file whose last access time is to be obtained.
Return value:
Returns a UNIX timestamp (seconds) representing the file's last access time.
Example of using
fileatime():
<code>$file = 'example.txt';
// Get the file's last access time
$lastAccessTime = fileatime($file);
// Format the timestamp as a readable date-time string
$lastAccessTime = date('Y-m-d H:i:s', $lastAccessTime);
// Output the result
echo 'File last access time: ' . $lastAccessTime;
</code>The example shows obtaining the timestamp, converting it with
date(), and echoing the formatted string.
Because
fileatime()returns a UNIX timestamp, you must use
date()or similar functions to format it.
You can also use
fileatime()for file management tasks, such as checking if a file hasn't been accessed for a certain period and performing cleanup.
<code>$file = 'example.txt';
// Get the file's last access time
$lastAccessTime = fileatime($file);
// Check if the file has not been accessed for more than 30 days
if (time() - $lastAccessTime > 30 * 24 * 60 * 60) {
// Perform cleanup, e.g., delete the file
unlink($file);
echo 'File deleted';
} else {
echo 'File recently accessed';
}
</code>This demonstrates using
fileatime()to decide whether to delete an old file or report recent access.
Summary
Using
fileatime(), you can easily obtain a file's last access time and apply further processing or decisions, making it a useful tool for file management in PHP.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.