如何从数据库中删除除大列表以外的所有文件?

I've a large list of files stored in the filesystem, some of them are mp4, jpgs and pdf

I want to erase all files except some of them extracted from a mysql query. e.g RandomMovie_04.mp4, AwesomeImage.jpg

This is my file structure

files/
    messages/
        images/
            45/ --> this is the ID in the DB
            46/
    articles/
        images/
            124/
            125/
        videos/
            124/
            207/

The files that I don't want to remove are extracted from the database

I'm using PHP (CakePHP) and MySQL

Tried this and it worked for one file, but I don't find a way for doing this with a list of files

find * -maxdepth 5 -not -name "RandomMovie_04.mp4" -type f -exec ls "{}" \; > list.txt

and this worked for two

find * -maxdepth 5 -not -name "RandomMovie_04.mp4" -not -name "AwesomeImage.jpg" -type f -exec ls "{}" \; > list.txt

I have to do this for all excluded files (in a php script)? like -not -name fileA -not -name fileB -not -name to_the_infinite...

Thanks

Sorry if my english sucks :(

If you can get an array of names from your PHP script, you could create the string for find like this:

<?php 
$files = array("RandomMovie_04.mp4", "AwesomeImage.jpg", "GreatDoc.pdf");
echo implode(' -or ', array_map(function($x) { return "-name '$x'"; }, $files));

Which outputs:

-name 'RandomMovie_04.mp4' -or -name 'AwesomeImage.jpg' -or -name 'GreatDoc.pdf'

Your find command could then be:

find /path/to/dir -not \(  $(php files.php) \) -delete

And find will delete all the files whose names were not found.

Note that you should run this from a separate directory, otherwise the PHP file will be deleted.