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.
The scandir() function in PHP is an inbuilt function that is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.
The scandir() function returns an array of files and directories of the specified directory.
The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.
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 } }
Better to use DirectoryIterator
$path = 'extracted'; // '.' for current foreach (new DirectoryIterator($path) as $file) { if ($file->isDot()) continue; if ($file->isDir()) { print $file->getFilename() . '<br />'; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With