Search code examples
phpfilewildcardglobunlink

Delete All Except Specific Files and Files With Specific Extension


I want to delete all files in a folder except files containing:

  1. Specific file names
  2. Specific file extensions

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?


Solution

  • 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
        }
    }