I have main folder named "gallery". In this folder there are some sub folders like "animal", "tree", etc. folder "animal" contains some pictures and so on. suppose i want to delete "animal" folder with all pictures in it, how can do this? i tried-
rmdirr($_SERVER['DOCUMENT_ROOT']."admin/gallery/animal");
but in server, it deleted the whole "gallery" folder with all in it. please tell me what i am doing wrong and also give m开发者_运维技巧e a solution. thanks in advance.
If there are no subfolders you can use glob()
to empty the directory before using rmdir()
:
foreach( glob( "/path/to/dir/*.*" ) as $filename ) {
unlink( $filename );
}
rmdir( "/path/to/dir" );
By the way, rmdir()
shouldn't delete any files. It just fails if the directory isn't empty. You might want to make sure there's nothing else in your code that causes the parent directory to be wiped out.
Just delete the directory recursively with a helper function:
rrmdir($_SERVER['DOCUMENT_ROOT']."admin/gallery/animal");
function rrmdir($path)
{
return is_file($path)
? @unlink($path)
: array_map('rrmdir', glob($path.'/*')) == @rmdir($path)
;
}
When removing a desired directory, you must first remove the files within that directory. Once that is complete, then you may remove the directory -- assuming you have the proper permissions.
Included below is code that removes the files in the directory and will then remove the specified directory itself:
<?php
$dirname = "animal";
function destroy($dir) {
$mydir = opendir($dir);
while(false !== ($file = readdir($mydir))) {
if($file != "." && $file != "..") {
chmod($dir.$file, 0777);
if(is_dir($dir.$file)) {
chdir('.');
destroy($dir.$file.'/');
rmdir($dir.$file) or DIE("Unable to delete $dir$file");
}else{
unlink($dir.$file) or DIE("Unable to delete $dir$file");
}
}
}
closedir($mydir);
}
destroyDir($dirname);
?>
精彩评论