Get all the files in the folder using scandir
, and use the NOT IN
clause to remove the files not in the folder.
$files = implode(scandir('files/'), "', '");
$db->query("DELETE FROM files WHERE file_name NOT IN('{$files}')");
If you want to do the opposite and delete the files which don't link up to a record in the database you can use a function called unlink
. This will delete the file. There's probably more optimized versions, but this is what I would do:
$files = implode(scandir('files/'), "', '");
$sth = $db->query("SELECT * FROM files WHERE file_name NOT IN('{$files')");
foreach($sth->fetchAll(PDO::FETCH_OBJ) as $file) {
unlink("files/{$file_name}");
}