Jump to content

Deleting Folder and contents with PHP


BOS45430

Recommended Posts

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);

Link to comment
https://forums.phpfreaks.com/topic/63472-deleting-folder-and-contents-with-php/
Share on other sites

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);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.