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

2022-01-01 00:00:00 directory php

我正在使用这段代码:

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

扫描用于 zip 上传的文件夹的目录.我希望能够在我的 $target 文件夹中找到所有文件夹,以便我可以删除它们及其内容,只留下 $target 目录中的文件.

一旦我返回了文件夹的内容,我不知道如何区分文件夹和文件才能删除文件夹.

另外,我被告知 rmdir() 函数无法删除其中包含内容的文件夹,有什么办法可以解决这个问题吗?

谢谢,本.

解决方案

使用is_dir()is_file() 函数确定你是否有文件夹或文件代码>

例如:

<前>$path = '提取/' .$名称[0];$results = scandir($path);foreach ($results as $result) {if ($result === '.' or $result === '..') continue;if (is_dir($path . '/' . $result)) {//如果目录使用的代码}}

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

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?

Thanks, Ben.

解决方案

To determine whether or not you have a folder or file use the functions is_dir() and 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
    }
}

相关文章