简体   繁体   English

使用scandir()查找目录中的文件夹(PHP)

[英]Using scandir() to find folders in a directory (PHP)

I am using this peice of code: 我正在使用这个代码:

$target = 'extracted/' . $name[0];  
$scan = scandir($target);

To scan the directory of a folder which is used for zip uploads. 扫描用于zip上传的文件夹的目录。 I want to be able to find all the folders inside my $target folder so I can delete them and their contents, leaving only the files in the $target directory. 我希望能够找到$target文件夹中的所有文件夹,这样我就可以删除它们及其内容,只留下$target目录中的文件。

Once I have returned the contents of the folder, I don't know how to differentiate between the folders and the files to be able to delete the folders. 一旦我返回了文件夹的内容,我不知道如何区分文件夹和文件以便能够删除文件夹。

Also, I have been told that the rmdir() function can't delete folders which have content inside them, is there any way around this? 另外,我被告知rmdir()函数无法删除其中包含内容的文件夹,有什么方法吗?

Thanks, Ben. 谢谢,本。

To determine whether or not you have a folder or file use the functions is_dir() and is_file() 要确定您是否有文件夹或文件,请使用函数is_dir()is_file()

For example: 例如:

$path = 'extracted/' . $name[0];
$results = scandir($path);

foreach ($results as $result) {
    if ($result === '.' or $result === '..') continue;

    if (is_dir($path . '/' . $result)) {
        //code to use if directory
    }
}

Better to use DirectoryIterator 最好使用DirectoryIterator

$path = 'extracted'; // '.' for current
foreach (new DirectoryIterator($path) as $file) {
    if ($file->isDot()) continue;

    if ($file->isDir()) {
        print $file->getFilename() . '<br />';
    }
}

First off, rmdir() cannot delete a folder with contents. 首先,rmdir()无法删除包含内容的文件夹。 If safe mode is disabled you can use the following. 如果禁用安全模式,您可以使用以下方法。

exec("rm -rf folder/"); 

Also look at is_dir()/is_file() or even better the PHP SPL . 另请参阅is_dir()/ is_file()或更好的PHP SPL

$directories = scandir('images');
foreach($directories as $directory){
    if($directory=='.' or $directory=='..' ){
        echo 'dot';
    }else{
            if(is_dir($directory)){
                  echo $directory .'<br />';
            }
    }
} 

a simpler and perhaps faster version 一个更简单,也许更快的版本

scandir will scan the entire directory, you can manually filter. scandir会扫描整个目录,可以手动过滤。

but if you are lazy like I am, then use glob 但如果你像我一样懒,那就用glob吧

$scan = glob($target."/*",GLOB_ONLYDIR);

and it will output an array of all your directories of your target. 它将输出目标所有目录的数组。

To get all the files in all the sub, sub folders 获取所有子文件夹中的所有文件

function myfunction($dir){

foreach ($dir as $dirname => $file) {

if(is_dir($file) &&  $file != '.' &&  $file != '..' ) { 

     // echo $file;
      $newDir = scandir($file);
      myfunction($newDir);

    }elseif($file !='.' && $file != '..'){

        echo "<br>File name is ---";
        echo  $file;
    }

} // end foreach


}  //function ends 

$dirpass = scandir($mypath3); // set directory
echo myfunction($dirpass); //     pass directory

We will get the result like below (plz ignore file names ) 我们将得到如下结果(plz忽略文件名)

File name is ----->index.PHP
File name is -----> 100000045   Invoices   Sales   Magento Admin.png
File name is -----> 100000142   Orders   Sales   Magento Admin(1).png
File name is -----> 100000142   Orders   Sales   Magento Admin.png
File name is ----->hrc-siberian-tiger-2-jpg_21253111.jpg
File name is ----->images (3rd copy).jpeg
File name is ----->images (4th copy).jpeg
File name is ----->images (5th copy).jpeg
File name is ----->images (another copy).jpeg
File name is ----->images (copy).jpeg
File name is ----->images.jpeg
File name is ----->JPEG_example_JPG_RIP_100.jpg
File name is ----->preload
File name is ----->Stonehenge (3rd copy).jpg
File name is ----->Stonehenge (4th copy).jpg
File name is ----->Stonehenge (5th copy).jpg
File name is ----->Stonehenge (another copy).jpg
File name is ----->Stonehenge (copy).jpg
File name is ----->Stonehenge.jpg

You also wanted to remove items if they were inside that directory. 如果项目位于该目录中,您还希望删除它们。 rmdir does not allow you to remove directories containing files. rmdir不允许您删除包含文件的目录。 But there is a simple sollution. 但是有一个简单的解决方案。

array_map('unlink', glob($target.'/*/*'));
array_map('rmdir',glob($target."/*",GLOB_ONLYDIR));

First it will unlink all the files in all sub-directories. 首先,它将取消链接所有子目录中的所有文件。
Secondly it will remove all directories, because they contain no files. 其次,它将删除所有目录,因为它们不包含任何文件。

If you got sub-sub-directories, then you should add another 2 lines like this: 如果你有子目录,那么你应该添加另外两行,如下所示:

array_map('unlink', glob($target.'/*/*/*')); //remove sub-sub-files
array_map('rmdir',glob($target."/*/*",GLOB_ONLYDIR)); //remove sub-sub-directories

array_map('unlink', glob($target.'/*/*')); //remove sub-files
array_map('rmdir',glob($target."/*",GLOB_ONLYDIR)); //remove sub-directories

The quick and dirty way: 快速而肮脏的方式:

$folders = glob("<path>/*", GLOB_ONLYDIR);

A more versatile and object-oriented solution, inspired by earlier answers using DirectoryIterator but slightly more concise and general purpose: 一个更通用,面向对象的解决方案,受到使用DirectoryIterator的早期答案的启发,但稍微简洁和通用:

    $path = '<path>';
    $folders = [];

    foreach (new \DirectoryIterator($path) as $file)
    {
        if (!$file->isDot() && $file->isDir())
        {
            $folders[] = $file;
        }
    }

here is one function i used mostly to parse archives and directories 这是我用来解析档案和目录的一个函数

function scan_full_dir($dir,$child=false){
    $dir_content_list = scandir($dir);
    foreach($dir_content_list as $value) 
    { 
        if($value === '.' || $value === '..') {continue;} 
        // check if we have file 
         if(is_file($dir.'/'.$value)) {
            echo '<br> File Name --> '.$value;
            continue; 
         }
        // check if we have directory
        if (is_dir($dir.'/'.$value)) {
            if(!$child){ 
                echo '<br> parent --> '.$value;
            }else{
                echo '<br> child of '.$child.' --> '.$value;    
            }
            scan_full_dir($dir.'/'.$value,$value);
        }       
    }   
}

output sample 输出样本

parent --> fonts
File Name --> standard
parent --> steps
child of steps --> pcb
File Name --> .attrlist.sum
File Name --> .profile.sum
File Name --> .stephdr.sum
File Name --> attrlist
child of pcb --> netlists
child of netlists --> cadnet
File Name --> .netlist.sum
File Name --> netlist
File Name --> profile
File Name --> stephdr

// to scan dir //扫描目录

scan_full_dir('path/of/myfolder');

// to scan archive without opening it , supported formats : gz, zip, tar and bz files. //扫描存档而不打开它,支持的格式:gz,zip,tar和bz文件。

scan_full_dir('phar://uploads/youarchive.zip);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM