How to get File Creation and Modification Date in PHP

Get File Creation, Modification and Access Date in PHP – Code Snippet

Here’s a featured example of how to get file dates in PHP. 

$file_stats = stat('my-file.txt');
 
if(!$file_stats) {
   echo 'Failed get file information';
}
 
else {
 
   echo 'The file was created on: '.date('d-m-Y h:m:i A',$file_stats["ctime"]).PHP_EOL; //Equivalent of filectime()
 
   echo 'The file was last modified on: '.date('d-m-Y h:m:i A',$file_stats["mtime"]).PHP_EOL; //Equivalent of filemtime()
 
   echo 'The file was last accessed on: '.date('d-m-Y h:m:i A',$file_stats["atime"]).PHP_EOL; //Equivalent of fileatime()
 
}
/*
OUTPUT
The file was created on: 13-09-2022 08:09:23 PM
The file was last modified on: 13-09-2022 09:09:35 PM
The file was last accessed on: 13-09-2022 09:09:36 PM
*/

Why are file dates significant? The article tries to answer this question, so stay tuned if you’re curious about it.

Relevant Content: PHP File System Functions

PHP has a huge library of FileSystem functions for various use cases involving files. You can get file creation, modification and access date in PHP, and that is what the article focuses on. Nevertheless, other functions can read, write, create and delete files. FuelingPHP includes some essential articles related to PHP files, for instance – How to delete a file in PHP.

However, no matter how sophisticated a file API is, it relies on the underlying system calls. As every operating system implements a file system in its own way, and that’s why some API calls can behave slightly different in different operating systems – for instance: Windows & Linux.

Anyways, the article includes notes about any possible discrepancy. So, what’s the wait for? Let’s jump to the good parts.

Scenario: Pushing Files to a Repository

Consider an online repository for files. This repository has a main file and contributors to that file. A contributor can push new changes to the main file, and others can receive a notification about the changes being made. Let’s list these functional requirements.

  • The repository saves one or more files.
  • Users can download and change files.
  • Users can push new changes to the repository.
  • The repository notifies users about the changes.
get file date php

A challenge in such a central repository architecture is consistency. If a user changes, the others should be able to update their local copies accordingly – otherwise, their records could go stale. There are numerous ways to implement this architecture, but this article is more inclined to use a file system.

We can use the popular observer-subscriber pattern to ensure every user is in the loop, but we need a trigger to initiate the notification process. One possible trigger would be file timestamp – creation, modification and last access. For instance – any change to the modification timestamp could trigger a notification process.

Let’s first ensure that we understand how to get file creation and modification date in PHP, and then we will be in a better position to take this scenario forward.

How to get File Creation Date in PHP with filectime()

PHP filectime()  returns the timestamp when a file’s metadata changes. Using this function in Windows returns a file’s creation time. Let’s view an example to learn more.

$filename = "my-file.txt";
 
if(file_exists($filename))
{
   $creationTimestamp = filectime($filename); //1663093380
   $creationDate = date("d-m-Y h:m:i A", $creationTimestamp);
   
   echo "The file was created on {$creationDate}";
}
 
else
{
   echo "The file {$filename} doesnot exist";
}
 
//Output
//The file was created on 13-09-2022 08:09:23 PM

The filectime() returns a file creation UNIX timestamp – the number of seconds from January 1st, 1970 UTC. 

Following that line of code, the example calls to date() with a format and timestamp string. The function constructs a date from that – in the ‘m-d-Y h:m:i A’ format. 

Note – File Creation Time in Linux

Most Linux kernels won’t pack in creation time in file metadata. It has a modification and access time, though. We will learn how to check file modification time in PHP.

How to get File Modified Date in PHP with filemtime()

The filemtime() in PHP returns the last modified timestamp in PHP. Let’s call this function on the file we created in the last example.

$filename = "my-file.txt";
 
if(file_exists($filename))
{
   $creationTimestamp = filemtime($filename);
   $modificationDate = date("d-m-Y h:m:i A", $creationTimestamp);
   
   echo "The file was last modified on {$modificationDate}";
}
 
else
{
   echo "The file {$filename} doesnot exist";
}
 
//Output
//The file was last modified on 13-09-2022 08:09:23 PM

Observe that the logic is almost the same except that we call filemtime(). Moreover, the output is the same because we have not modified the file yet. Let’s add a line to the file.

filemtime PHP

Cool! Let’s rerun the program to see the output now.

//Output
//The file was last modified on 13-09-2022 09:09:27 PM

Voila! The function works like a charm! 

There is yet another similar function for file access time in PHP. Let’s learn about that in the following section.

How to get File Access Date in PHP with fileatime()

PHP fileatime() returns the file’s last access time. It is similar to the last two functions in terms of use. Let’s see this function in action.

$filename = "my-file.txt";
 
if(file_exists($filename))
{
   $creationTimestamp = fileatime($filename);
   $accessDate = date("d-m-Y h:m:i A", $creationTimestamp);
   
   echo "The file was last accessed on {$accessDate}";
}
 
else
{
   echo "The file {$filename} does not exist";
}
 
//Output
//The file was last accessed on 13-09-2022 09:09:27 PM

Perfect! The access timestamp suggests that we accessed the file last time on ‘13-09-2002 09:09:27 PM’, which is the exact time we modified it. Let’s access it once more and see if the output changes.

//Output
//The file was last accessed on 13-09-2022 at 09:09:35 PM

Yes, it does. Awesome!

PHP filesystem functions feature another cool function that returns an array of all the information about a file, including creation, modification and access times. Let’s review that.

How to get File Creation, Modification & Access Dates in PHP with stat()

PHP stat() returns an array that includes information about a file. Let’s see this function in the following example.

$file_stats = stat('my-file.txt');
 
if(!$file_stats) {
   echo 'Failed get file information';
}
 
else {
 
   echo 'The file was created on: '.date('d-m-Y h:m:i A',$file_stats["ctime"]).PHP_EOL; //Equivalent of filectime()
 
   echo 'The file was last modified on: '.date('d-m-Y h:m:i A',$file_stats["mtime"]).PHP_EOL; //Equivalent of filemtime()
 
   echo 'The file was last accessed on: '.date('d-m-Y h:m:i A',$file_stats["atime"]).PHP_EOL; //Equivalent of fileatime()
 
}
/*
OUTPUT
The file was created on: 13-09-2022 08:09:23 PM
The file was last modified on: 13-09-2022 09:09:35 PM
The file was last accessed on: 13-09-2022 09:09:36 PM
*/

Awesome! With stat(), we retrieve file information in one array. To view the full list of stats, consider reading the official documentation.

Now, as we are comfortable with PHP file dates, it’s time to move forward with our File Repository scenario.

Designing File Repository in PHP – A Concept

Keeping in view the scenario at the start of the article, we discussed some important pointers. To get a bird’s eye view of the application’s design, we will use a class diagram to frame out important building blocks and how they fit together.

PHP file repository class diagram

The User and Repository entities are self-explanatory and represent the two most important components of the file repository. The repository includes an array of users and uses the notify function to send updates to users about any changes to the file in the repository.

The Event class listens to that change and triggers a notification spree for users. So, what is the change that would trigger the Event? This particular example would be a change in file modification time.

As this is a hypothetical application, we won’t be giving away any source code, but here’s a crude example of the idea.

class Event {
 
   public function trigger($users) {
      foreach($users as $user) {
         console.log("{$user} has been notified");
      }
   }
}
 
//The notify function calls the trigger function on event object.
function notify($event, $users) {
   $event->trigger($users);
}
 
 
$users = ["User1", "User2", "User3", "User4"];
 
$fileName = "my-file.txt";
 
if(file_exists("my-file.txt")) {
 
   while($programRunning) {
 
      $lastModified = filemtime("my-file.txt");
 
       $currentModifiedTime = filemtime("my-file.txt");
 
      if($currentModifiedTime - $lastModified > 0) {
         $event = new Event();
         notify($event, $users);
      }
 
   }
   
}

The above example is more of a pseudocode of the entire flow of the notification functionality only. The Event class has a trigger method that expects an array of users and loops over them (actual implementation will send an Email to the users)

We have mocked the notify method too. The main program compares the last modification with the recent modification time and issues a notify() call.

Now, this implementation is nowhere perfect, but it does solidify the idea of what the functionality is all about and also signifies the use of file dates and times in PHP.

Cool! Guess that’s it; let’s move on to the conclusion.

Conclusion

Wrap Up

This article concerns PHP file dates and times at creation, modification and access. The examples in the article use PHP filesystem functions – filectime, fiemtime and fileatime for creation, modification and access times.

Following these, the stat() function section sheds some light on how to retrieve file information in an array instead of independently calling these functions. Lastly, the article concludes with the hypothetical File Repository application that relies on file modification times for notifying users about file changes.

Hope you’ve liked the article. Stay tuned for more at FuelingPHP!

Classes and Functions Mentioned

filectime – (PHP 4, PHP 5, PHP 7, PHP 8) This function returns the inode change time of the file – when the file metadata changes.

filemtime – (PHP 4, PHP 5, PHP 7, PHP 8) This filesystem function returns the last modified time of the file.

fileatime – (PHP 4, PHP 5, PHP 7, PHP 8) This PHP filesystem function returns the last access time of the file.

stat – (PHP 4, PHP 5, PHP 7, PHP 8) This function returns an array of file related information.

file_exists – (PHP 4, PHP 5, PHP 7, PHP 8) This function checks if a file exists.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


Article Categories

Article Tags

© 2022 Confident.Systems