繁体   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