Delete files which are not in a mySQL TABLE

2019-08-08 06:45发布

问题:

I'm trying to delete files (picture files) in a folder only if they're not present in a specific database table.

Just like a check of filenames and if they're present in the table it's ok but if not delete them.

Any ideas how to do that?

回答1:

Just select all pictures that shouldn't be deleted from database and go through all files.

$result = mysql_query("SELECT filename FROM no_delete");
while($row = mysql_fetch_assoc($result)) {
   $do_not_delete[] = $row['filename'];
}

foreach(glob("*") as $filename) {
    if (!in_array($filename, $do_not_delete)) {
        //delete them
    }
}


回答2:

I would approach this by writing a script which takes a listing of all the files in the directory, stores them in an array (since you are using php) and then one by one queries your database to see if they exist in the table.

If they do, then do nothing, if they don't then delete it.

It would also be helpful to capture in a log file the names of the ones you have deleted just for history.

You can run this at the command line using curl and even set it up as a chron job (if you are on linux) or a scheduled task (on windows) so it will run automatically.



回答3:

Use scandir() http://php.net/manual/en/function.scandir.php to get the contents of the folder and for every array value check if the filename is present in the table. If not, delete the file with unlink() http://www.php.net/manual/en/function.unlink.php