Backend Development 4 min read

Using PHP fileatime() to Retrieve File Access Timestamps and Implement Access Tracking

This article explains how to use PHP's fileatime() function to retrieve a file's last access timestamp, demonstrates basic and advanced usage with code examples, shows how to check whether a file has been accessed, and illustrates implementing simple access count tracking.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP fileatime() to Retrieve File Access Timestamps and Implement Access Tracking

Basic Usage of fileatime()

The fileatime() function is part of PHP's filesystem functions and returns the last access time of a file. It requires only the file path as an argument. For example, the following code obtains the access timestamp of example.txt :

<code>$file = "example.txt";
$timestamp = fileatime($file);
</code>

The variable $timestamp now holds the file's access time, which can be used for further processing.

Using fileatime() to Determine If a File Has Been Accessed

In some scenarios you may need to know whether a file has ever been accessed. By checking the value returned by fileatime() , you can implement this logic. Below is a sample implementation:

<code>$file = "example.txt";
$lastAccessed = fileatime($file);

if ($lastAccessed > 0) {
    echo "File has been accessed!";
    // additional handling...
} else {
    echo "File has not been accessed!";
}
</code>

If the timestamp is greater than zero, the file has been accessed and you can perform the appropriate actions.

Combining fileatime() for File Access Statistics

To keep a count of how many times a file has been accessed, you can store the count in a separate file and update it each time the target file is accessed. The following example demonstrates this approach:

<code>$file = "example.txt";
$accessCountFile = "access_count.txt";

$accessCount = 0;
if (file_exists($accessCountFile)) {
    $accessCount = file_get_contents($accessCountFile);
}

$accessCount++;
file_put_contents($accessCountFile, $accessCount);

echo "File has been accessed " . $accessCount . " times";
</code>

Each access increments the counter, which is saved back to access_count.txt , allowing you to monitor file usage in real time.

Conclusion

By now you should understand how to use PHP's fileatime() function for retrieving file access timestamps, checking access status, and implementing simple access counting. Proper use of this function can make your file‑handling code more efficient and reliable.

BackendPHPfilesystemfileatimefile access timestamp
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

login 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.