skip to Main Content

Dynamically I am creating sub directory in a folder and I need to get the last created directory in a sting format, I have tried many ways but failed to get it. What i have tried is,

$path = "/path/to/my/dir";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
 }
}

But it works for only file.
Thanks in advance.

2

Answers


  1. Started as comments – but there were so many!

    But it works for only file

    change is_file to is_dir

    and $path is full url

    $path in the above is not a URL, its a path. is_dir/is_file/filectime won’t work for URLs

    Also you’ve flagged this as cpanel which would be a reason for closing this as off-topic, but its not relevant to a coding problem. OTOH it does hint that this is not a MSWindows platform. On Unix and Linux, filectime() actually returns the filemtime. So the information it shows will not accurately reflect the creation time.

    Login or Signup to reply.
  2. Try something like this:

    $path = "/path/to/my/dir";
    $latest_mtime = 0;
    $latest_filename = '';
    if ($handle = opendir($path)) {
        $blacklist = array('.', '..');
        while (false !== ($file = readdir($handle))) {
            if (!in_array($file, $blacklist)) {
                if (is_dir($file) && filemtime($file) > $latest_mtime) {
                    $latest_mtime = filemtime($file);
                    $latest_filename = $file;
                }
            }
        }
        closedir($handle);
    }
    

    Also,
    you can change the condition of the blacklist for:

    if (!in_array($file, $blacklist) && substr($file, 0, 1) != ".") {
    

    to exclude hidden directories (in unix-like sistems).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search