How do I delete all files in a directory if I don't know the names of the files? I would think I would want to do some kind of
file_delete()
but don't know if there's a way to have it delete all files that it finds in a certain directory?
delete all files in a directory?
So, this is almost the along the same lines as my other post but not really and since I'm not that well versed in this I'm kinda stumped. So somehow I need to start out with this
$dir_path="../../Audio-MP3/Uploads/".$WebPage."/".stripslashes($Row["Directory"]);
if (is_dir($dir_path) && ($dir_handle = opendir($dir_path))) {
if (readdir($dir_handle) === false) {
rmdir($dir_path);
}
}
and put a type of else in there so that it says if readdir($dir_handle) is false go ahead and delete the directory but if there's something in there then delete the files so that you can delete the directory. Unless there's some sort of override that I could use instead of rmdir?
// remove trailing slash from path
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory))
{
// ... we return false and exit the function
return FALSE;
// ... if the path is not readable
}elseif(!is_readable($directory))
{
// ... we return false and exit the function
return FALSE;
// ... else if the path is readable
}else{
// we open the directory
$handle = opendir($directory);
// and scan through the items inside
while (FALSE !== ($item = readdir($handle)))
{
// if the filepointer is not the current directory
// or the parent directory
if($item != '.' && $item != '..')
{
// we build the new path to delete
$path = $directory.'/'.$item;
// we remove the file
unlink($path);
}
}
// close the directory
closedir($handle);
}
or if your unix server allows exec()
exec("rm -rf $directory");
or
rm -rf $directory
;
Any host worth their security does not allow exec, as for rm -rf, he did not say delete any sub-folders also, just files. Besides, rm -rf is a very dangerous way to do things, its much safer to traverse the folder unlinking files.
I own my own servers. Lots of people do. Don't know what this programmer's situation is: I can use exec() if I please. Maybe he/she can too.
As to my method removing the directory, the poster says:
...delete the directory but if there's something in there then delete the files so that you can delete the directory. Unless there's some sort of override that I could use
and includes this code:
rmdir($dir_path);
So I might assume s/he means to remove the directory.