BOS45430 Posted August 5, 2007 Share Posted August 5, 2007 Im using this code to delete a folder using my script but it says Directory not empty. What code could i use that will delete the folder, subfolders, and all its contents. $currentdir = getcwd(); $directory="$currentdir/users/$_COOKIE[username]/albums/$_GET[albumname]"; rmdir($directory); Quote Link to comment https://forums.phpfreaks.com/topic/63472-deleting-folder-and-contents-with-php/ Share on other sites More sharing options...
teng84 Posted August 5, 2007 Share Posted August 5, 2007 first delete the content of that dir you want to remove by using the unlink and readdir http://www.php.net/manual/en/function.readdir.php and http://www.php.net/manual/en/function.unlink.php Quote Link to comment https://forums.phpfreaks.com/topic/63472-deleting-folder-and-contents-with-php/#findComment-316310 Share on other sites More sharing options...
Fadion Posted August 6, 2007 Share Posted August 6, 2007 As teng84 said a dir must be empty before removal. U can use the following script to loop through a directory, delete all its files and finally remove the dir itself. I made it on the fly and its not as flexible as it deletes only a sub directory but maybe u can modify to fit your needs. $directory = 'data'; $dir = opendir($directory); while(FALSE !== ($file = readdir($dir))){ if($file == '.' or $file == '..') {continue;} if(is_file($directory . "/" . $file)){ unlink($directory . "/" . $file); } else{ $subDirectory = $directory . "/" . $file; $subdir = opendir($subDirectory); while(FALSE !== ($subdirFile = readdir($subdir))){ if($subdirFile == '.' or $subdirFile == '..') {continue;} unlink($directory . "/" . $file . "/" . $subdirFile); } rmdir($subDirectory); } } rmdir($directory); Quote Link to comment https://forums.phpfreaks.com/topic/63472-deleting-folder-and-contents-with-php/#findComment-316347 Share on other sites More sharing options...
Fadion Posted August 6, 2007 Share Posted August 6, 2007 or u can go in a shell approach, but dont know, guess its better a pure php approach. $directory = 'data'; exec('rm -rf ' . $directory); Quote Link to comment https://forums.phpfreaks.com/topic/63472-deleting-folder-and-contents-with-php/#findComment-316353 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.