Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 491
Patrioticcow Avatar asked Aug 10 '12 23:08

Patrioticcow


1 Answers

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.

like image 145
HappyTimeGopher Avatar answered Oct 09 '22 00:10

HappyTimeGopher