dongwopu8210
dongwopu8210
2017-11-28 16:08
浏览 41
已采纳

如何在PHP中获取最后创建的目录?

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条回答 默认 最新

  • douchun1961
    douchun1961 2017-11-28 16:15
    已采纳

    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).

    点赞 评论
  • dozrhldy285751
    dozrhldy285751 2017-11-28 16:15

    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.

    点赞 评论

相关推荐