I want to delete files from multiple direcories in PHP. The problem is when the code is run it deletes everything. I have a main folder which has a lots of folders in it. Those folders have files that i want to delete except that file in $filesToKeep variable. I'm a beginner PHP developer, and i really don't know how could i find the problame. If there is an another easier way to delete those files could be helpful too.
Here is my code:
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
$filesToKeep = array(
'partner-profil-480.jpg'
);
$dirList = glob('*');
foreach ($dirList as $file) {
if (!in_array($file, $filesToKeep)) {
if (is_dir($file)) {
rrmdir($file);
} else {
unlink($file);
}//END IF
}//END IF
}//END FOREACH LOOP
?>
My Answer:
'.' && $object != '..') {_ if (is_dir($dir.'/'.$object)) {_ rrmdir($dir.'/'.$object);_ } else {_ unlink($dir.'/'.$object);_ }_ }_ }_ rmdir($dir);_ }_}_$mainFolder = 'path/to/main/folder';_$filesToKeep = ['image.jpg'];_rrmdir($mainFolder);
Rate this post
4 of 5 based on 5995 votesComments