簡體   English   中英

在PHP中刪除超過2天的文件夾中所有圖像文件的正確方法

[英]The correct way to delete all images files in a folder older than 2 days in PHP

我想刪除所有超過 2 天或我想添加的任意天數的圖像。 我將在 cron 作業中添加該文件,該文件將在 X 天工作。 我已使用以下代碼來執行此操作。

    <?php
    $folderName='uploads';
    if (file_exists($folderName)) {
        foreach (new DirectoryIterator($folderName) as $fileInfo) {
            if ($fileInfo->isDot()) {
            continue;
            }
            if ($fileInfo->isFile() && time() - $fileInfo->getCTime() >= 2*24*60*60) {
                unlink($fileInfo->getRealPath());
            }
        }
    }
    ?>

此代碼未提供任何錯誤,但未從文件夾中刪除圖像。 我從互聯網上嘗試了許多其他代碼,但沒有成功。 所以我需要這個小小的幫助。

你可以試試這個代碼

<?php
$path = '/path/to/files/';
if ($handle = opendir($path)) {

    while (false !== ($file = readdir($handle))) { 
        $filelastmodified = filemtime($path . $file);
        //24 hours in a day * 3600 seconds per hour
        if((time() - $filelastmodified) > 24*3600)
        {
           unlink($path . $file);
        }

    }

    closedir($handle); 
}
?>

你可以像這樣從php調用shell命令,

find /data/haoqi_backup/db_code/db* -mtime +2 -exec rm {} \\;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM