如何在删除服务器上文件夹中的所有文件后返回“TRUE”


How to return "TRUE" after deleting all files in a folder on my server?

我有这个功能可以删除文件夹的内容:

// Delets the content of the "files/weekly_reports/" folder.
public function delete_pdf(){
        // get all file names
        $files = glob('files/weekly_reports/*'); 
        foreach($files as $file){ // iterate files
            if(is_file($file))
            unlink($file); // delete file
            }
        }

在 for 循环中运行此函数时,PHP 代码继续运行,尽管它尚未完成删除过程(我认为),因此 - 跳过进程,因为它返回 FALSE。

所以我添加了另一部分:

// Delets the content of the "files/weekly_reports/" folder.
public function delete_pdf(){
    // get all file names
    $files = glob('files/weekly_reports/*'); 
    foreach($files as $file){ // iterate files
        if(is_file($file))
        unlink($file); // delete file
    }

    if (empty($files)){
        return TRUE;
    } else {
        return FALSE;
    }
}

所以我得到了相同的结果。

如何确保文件夹 100% 为空并使循环运行没有任何问题。

对于好奇的人,以下是调用该函数的主要代码:

public function main_weekly_report(){
    $today = date('Y-m-d');
    $reports = $this->kas_model->get_wr_table();
    foreach ($reports as $report) {
        // Outputs the current report that it is on. 
        var_dump($report);
        // Delete the content of the folder containing the PDFs
        if ($this->delete_pdf()){
            // Creates a new PDF
            $this->create_pdf($report->wr_app_id, $report->wr_date1, $report->wr_date2, $report->wr_date3);
            // Increment "dates" to next week.
            // $this->kas_model->weekly_inc_date($report->wr_id, 'wr_date1', $today);
            // $this->kas_model->weekly_inc_date($report->wr_id, 'wr_date2', $today);
            // Sends to the report to the customer:
            if ( $this->is_connected() ) {
                $this->send_pdf_customer($report->wr_app_id);
                echo "Sent to customer!";
            }
        }
    }
}

在这一行中,if (empty($files)){$files 仍然是您在 $files = glob('files/weekly_reports/*'); 中获得的相同文件名数组。

取消文件链接会删除对文件系统中文件的引用,但不会影响内存中数组的内容。

您可以通过在方法结束时在测试中再次运行glob()来重新填充它。

你的代码是对的。您只是错过了在文件系统中删除元素后unset()元素。试试这个在你的foreach.

foreach($files as $key=>$file){ // iterate files
    if(is_file($file))
    {
      if(unlink($file))
      {
         unset($files[$key]);
      } // delete file
    }
}

那么,这将起作用

if (empty($files)){
   return TRUE;
} else {
   return FALSE;
}

输出:真