Reputation: 36
How would I delete a folder including it's contents with PHP? I know I would use some form of a loop but am not sure what type or what approach I would have to take. I use the following to delete files and want to incorporate it in there:
if(isset($_REQUEST['DelFile'])) {
$DeleteFile = $_REQUEST['DelFile'];
if(file_exists($directory.$DeleteFile)) {
@unlink($directory.$DeleteFile);
rmdir($directory.$DeleteFile);
$files = glob($directory . $file); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
@header("location:interface.php?msg=1");
} else @header("location:interface.php?msg=2");
}
Upvotes: 0
Views: 295
Reputation: 146
You may try this code to get all files in folder then unlink all files using loop
$files = glob('uploads/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
Upvotes: 1
Reputation: 36
All I had to do was setup a loop that will delete the files. After the loop I delete the directories.
if(isset($_REQUEST['DelFile_folder'])) {
$DeleteFile = $_REQUEST['DelFile_folder'];
if(file_exists($directory.$DeleteFile)) {
@unlink($directory.$DeleteFile.'/index.php');
rmdir($directory.$DeleteFile . '/uploads/' . $_SESSION['user']);
rmdir($directory.$DeleteFile . '/uploads');
rmdir($directory.$DeleteFile);
$dir = 'uploads/' . $_SESSION['user'] . '/' . $DeleteFile . '/uploads/';
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if(!is_dir($file)) {
unlink ("$dir"."$file");
}
}
closedir($dirHandle);
@header("location:interface.php?msg=1");
} else @header("location:interface.php?msg=2");
}
Upvotes: 0
Reputation: 47321
Why not just run a rm -rf $directory
?
system("rm -rf $directory");
Upvotes: 1