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.

php Courses
php Courses
php Courses
How to Retrieve and Use File Last Access Time with PHP's fileatime()

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().

int fileatime ( string $filename )

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():

$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;

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.

$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';
}

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentPHPfile managementfile access timefileatime
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.