Reputation:
i want to delete all the directory content except some files there is a description :
the reason why i need to delete all the content except those files cause the other files (that i want to delete them) is generated so i don't know their names,there is some idea to do so? this is the script i try to create it :
<?php
$filesToKeep = array(
'index.php',
'i.php',
'c.php'
);
$dirList = glob('*');
foreach ($dirList as $file) {
if (! in_array($file, $filesToKeep)) {
unlink($file);
}//END IF
}//END IF
}//END FOREACH LOOP
?>
Upvotes: 0
Views: 1051
Reputation:
thanks to @Mic1780 we could do this but it keeps returning the error :
'directoryName' is not empty
so we need a recursive function to do that and this is the whole code :
<?php
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(
'iall.php',
'a0a058baaeef16e88f6bd2ee36c03f6f',
'index.php',
'a0a058baaeef16e88f6bd2ee36c03f6f.php',
'c.txt',
'i.php',
'c.php'
);
$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
?>
Upvotes: 1
Reputation: 1794
As Mark mentioned in a comment, the way I would remove all files except specific ones in a directory would be to use glob
.
<?php
$filesToKeep = array(
'index.php',
'i.php',
'c.php'
);
$dirList = glob('*');
foreach ($dirList as $file) {
if (! in_array($file, $filesToKeep)) {
if (is_dir($file)) {
rmdir($file);
} else {
unlink($file);
}//END IF
}//END IF
}//END FOREACH LOOP
?>
Place all file names in the $filesToKeep
array that you want to keep. When the foreach loop is ran, it will keep all files that are found in the $filesToKeep
array. Maybe before actually running this with the unlink
function you might want to just echo files that would be deleted to screen first so that you do not accidentally delete ones you want to keep.
Upvotes: 1