澄清 - 删除不在 mySQL TABLE 中的文件

Clarifcation - Delete files which are not in a mySQL TABLE

Delete files which are not in a mySQL TABLE

上面的 link 是针对 Stack Overflow 问题的,答案(我相信)非常接近我正在寻找的答案。我实际上只是想进一步澄清给出的答案。


问题

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?

接受的答案

$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
    }
}

我对 PHP 不太了解,但我不相信他们在这里指定服务器上的文件夹路径,是吗?我希望能够查看特定文件夹并检查该文件夹中的任何图像是否在任何数据库表中。如果不是,请删除该图像。

在调用 glob("*") 之前只需添加一行 chdir("")。然后你可以搜索你想看的目录。我刚刚在下面的电话中上升了一个级别。您可以指定您想要的任何目录。在执行删除之前,只需将 echo 语句添加到 $filename 以验证是否正在删除正确的文件。

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

this answer the first parameter, i.e. pattern, can contain the path to a directory relative to the current working directory of the script (which can be changed with chdir()中所述)或绝对路径。

考虑来自 this tutorial page 的这个例子:

$dir = "/etc/php5/*";

// Open a known directory, and proceed to read its contents
foreach(glob($dir) as $file) 
{
    echo "filename: $file : filetype: " . filetype($file) . "<br />";
}