phpdelete-fileunlinkremoveall

How to delete all files except one from a directory using PHP?


I have a few directories with some files in them:

/test1/123.jpg
/test1/124.jpg
/test1/125.jpg
/test2/123.jpg
/test2/124.jpg

I want to delete all except for /test1/124.jpg or /test2/124.jpg?

I know the directory name and the file name. Is there a way of doing that in a Linux environment with php and maybe unlink?


Solution

  • 8 years ago I wrote this quick hack that got accepted but please take on account that

    However it has the advantage of running all deletions in a single shell command and it does not require an extra exclusion lookup per processed file, which makes it run quite fast on high deletion vs. preserving ratios, if performance is what you are looking for:

        for ($i=1;$i<=2;$i++){
            shell_exec ('mv /test'.$i.'/124.jpg /test'.$i.'/keep.jpg');
            shell_exec ('rm /test'.$i.'/12*.jpg');
            shell_exec ('mv /test'.$i.'/keep.jpg /test'.$i.'/124.jpg');
        }
    

    Anyway if you look right here a few other answers that propose an unlink based solution were added after mine, which (as discussed in the comments below) is a much better approach, to which I'd also suggest