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

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.


Perhaps a little crude, but if you're on a Linux system you could do this (assuming you're in the correct directory):

<?php shell_exec('rm $(ls * | grep -v '.$fileYouWantToKeep.')'); ?>

You will obviously need to filter that variable if contains any user input though.