-2

Possible Duplicate:
get last modified file in a dir?

I have lot of file inside a folder. How can I get the last modified file name using php?
Is it possible? kindly help me.Thanks in advance.

Community
  • 1
  • 1
yogi46
  • 53
  • 1
  • 7

2 Answers2

3

Yes, it is possible. Please refer this method: http://php.net/manual/en/function.filemtime.php

In order to work list all files in a folder an get the filemtime. Compare them and you will find the latest updated file in that folder.

Remember that, this method will return in UNIX time() but not a date like (YYYY/mm/dd)

UPDATE: Finding most new file is directly is not possible. You have to check files by one by.

<?php
function findMostNewFile($folder) {
     $files = array();

     foreach (scandir($folder) as $file) {
         $path = $folder . DIRECTORY_SEPARATOR . $file;
         if (is_dir($path)) continue; // do not count folders. only files.
         $files[filemtime($path)] = $path;
     }
     krsort($files);

     $arr = array_slice($files, 0, 1); // return the first newest file's path as array
     return $arr[0]; // return only a path and name as a string
}
?>

Thats all.

UPDATE: return as string.

flower58
  • 687
  • 2
  • 8
  • 15
  • Thank you for your responce Gencer.I think filemtime for a specific file? but i want to find last modified file name inside a directory. – yogi46 Feb 28 '12 at 13:03
  • Your welcome. I understand what you need. You can't do that by directly. There is no any function/method to do this job. All you have to do is grab all files in a folder with read and get their filemtime. Plase look at my post. I upodated it by ur needs. – flower58 Feb 28 '12 at 13:10
  • Sorry Gencer! I got this "Warning: array_slice() expects parameter 1 to be array, boolean given". – yogi46 Feb 28 '12 at 13:44
  • Sorry too. I fixed the file. please check again. i tested it and working properly. Now it returns file path and name. – flower58 Feb 28 '12 at 14:01
  • wow!!Great! Thank you so much Gencer. Its work!! – yogi46 Feb 28 '12 at 15:05
  • Your welcome! It's glad to see it works for you. Please mark this answer as accepted if possible. Best regards, Gencer. – flower58 Feb 28 '12 at 16:32
0

I'm pretty sure you'll have to look through all files and grab the max mod time. Use 'glob' to loop through files and use filemtime() to grab the file mod date/time.

Luc
  • 985
  • 7
  • 10