-1

/The png files have random names, so how would I manage to extract the latest addition to the file?/

The user creates a PNG file, which is stored in folder (/temp). This directory has hundreds of previously created PNG files. How can I extract the last addition to the file using the time of creation?

PMoran
  • 1
  • [`filectime()`](http://php.net/manual/en/function.filectime.php), [`array_multisort()`](http://php.net/manual/en/function.array-multisort.php). Alternatively, store the the filenames and upload times in a database. – Gerald Schneider Mar 02 '16 at 14:47
  • 2
    Possible duplicate of [PHP: Get the Latest File Addition in a Directory](http://stackoverflow.com/questions/1491020/php-get-the-latest-file-addition-in-a-directory) – Charlie Mar 02 '16 at 14:53

1 Answers1

0

If you don't want to give a name to your files through which you can extract the last one, or, if you don't want to record somewhere the name of the last file added, I'm afraid the only way is to traverse through all files and get the last modified one.

$path = "/path/to/my/dir"; 

$latest_ctime = 0;
$latest_filename = '';    

$d = dir($path);
while (false !== ($entry = $d->read())) {
  $filepath = "{$path}/{$entry}";
  // could do also other checks than just checking whether the entry is a file
  if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
    $latest_ctime = filectime($filepath);
    $latest_filename = $entry;
  }
}

I got the answer from this question.

Community
  • 1
  • 1
Charlie
  • 22,886
  • 11
  • 59
  • 90