Forum Moderators: coopster

Message Too Old, No Replies

PHP Find Newest Directories/Files

help fixing a script

         

cookiemonster

2:04 am on May 21, 2010 (gmt 0)

10+ Year Member



Hi,

I recently found this PHP script on another forum - it supposedly puts all files in a specified directory in an array from newest to oldest, then returns the newest file by doing array[0].

Is there any way this script can be applied to get the newest DIRECTORIES instead of files? i.e., whichever directory was last added/modified?

Thanks in advance for any help, here is the code:

<?php
$path = "docs/";
// show the most recent file
echo "Most recent file is: ".getNewestFN($path);

// Returns the name of the newest file
// (My_name YYYY-MM-DD HHMMSS.inf)
function getNewestFN ($path) {
// store all .inf names in array
$p = opendir($path);
while (false !== ($file = readdir($p))) {
if (strstr($file,".inf"))
$list[]=date("YmdHis ", filemtime($path.$file)).$path.$file;
}
// sort array descending
rsort($list);
// return newest file name
return $list[0];
}
?>

Alcoholico

2:28 pm on May 21, 2010 (gmt 0)

10+ Year Member



This function should do it, though I've not tested it :

function getNewestDir ($path) {
if ($p = opendir($path) ) {
while (false !== ($file = readdir($p))) {
if (is_dir($file)) {
$list[] = date('YmdHis', filemtime($path.$file)).$path.$file;
}
}
rsort($list);
return $list[0];
}
return false;
}

cookiemonster

1:13 pm on May 22, 2010 (gmt 0)

10+ Year Member



@Alcoholico

I can't seem to get that to work ... are there any other variables or functions that need to be included?

Thanks.

Alcoholico

6:10 pm on May 22, 2010 (gmt 0)

10+ Year Member



Sorry, don't blame though. It looks like a php bug to me; from a user comment on php.net:
The function is_dir will always return false if the handle acquired with opendir is not from the current working directory (getcwd); exception applies to "." and "..". Thus, if you need a consistent dir listing from any directory other than the current one, you must change dir first.

I changed the function to switch directories:
<?php
function getNewestDir($path) {
$working_dir = getcwd();
chdir($path); ## chdir to requested dir
$ret_val = false;
if ($p = opendir($path) ) {
while (false !== ($file = readdir($p))) {
if ($file{0} != '.' && is_dir($file)) {
$list[] = date('YmdHis', filemtime($path.'/'.$file)).$path.'/'.$file;
}
}
rsort($list);
$ret_val = $list[0];
}
chdir($working_dir); ## chdir back to script's dir
return $ret_val;
}

?>

Keep in mind that during the function execution the system will change momentarily to the requested directory, and that you should supply full paths.