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

Patrioticcow picture Patrioticcow · Aug 11, 2012 · Viewed 7.5k times · Source

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?

Answer

HappyTimeGopher picture HappyTimeGopher · Aug 11, 2012

Just edit $dir and $leave_files to edit the locations and files.

$dir = 'test1';
$leave_files = array('124.jpg', '123.png');

foreach( glob("$dir/*") as $file ) {
    if( !in_array(basename($file), $leave_files) ){
        unlink($file);
    }
}

You'd run that once for each directory.

Also remember to make $dir a full path (with no trailing slash) if the target directory isn't in the same folder as this script.