I want to delete all files in a folder except files containing:
The following code succeeds in the above first point, but not the second point.
function deletefiles()
{
$path = 'files/';
$filesToKeep = array(
$path."example.jpg",
$path."123.png",
$path."*.mkv"
);
$dirList = glob($path.'*');
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
}
How can I achieve both conditions?
You need to change a bit your function:
<?php
function deletefiles()
{
$path = 'files/';
$filesToKeep = array(
$path . "example.jpg",
$path . "123.png",
);
$extensionsToKeep = array(
"mkv"
);
$dirList = glob($path . '*');
foreach ($dirList as $file) {
if (!in_array($file, $filesToKeep)) {
if (is_dir($file)) {
rmdir($file);
} else {
$fileExtArr = explode('.', $file);
$fileExt = $fileExtArr[count($fileExtArr)-1];
if(!in_array($fileExt, $extensionsToKeep)){
unlink($file);
}
}//END IF
}//END IF
}
}