Search code examples
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

    • It is platform dependent: It will work on unix-like systems only, as it depends on unix-like paths and rm and mv delete and move shell commands.
    • It requires php config to allow running system shell commands via shell_exec (Something I would not recommend unless you know what you are doing)
    • It is quite an ad-hoc answer to the proposed question, not even fancy enough to use a foreach iteration on an array of file names, which allows for a much more general solution.
    • It does not perform error capture of any kind so your script will silently continue on failure (Also capturing errors on shell_exec is not trivial since you do not get the exit code as you can do with alternatives like exec or system)

    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

    • Adding error handling, as unlink might fail to delete an existing file on permission issues when the file is in use or the script execution user is not allowed to modify it.

    • Always ini_get('max_execution_time'); to check your script execution timeout settings (and consider using set_time_limit to extend it for your script if necessary) before running a script processing an unknowingly long list of files.