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

Best Solution

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