HarsimranSingh
HarsimranSingh

Reputation: 21

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

I want to delete all images those are older than 2 days or any number of days I want to add. I will add that file in cron job which will work on X no of days. I have used the below code for preforming this action.

    <?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());
            }
        }
    }
    ?>

This code is not providing any error but Its not deleting images from the folder. I have tried many other codes from Internet but no success. So I need this small help.

Upvotes: 1

Views: 393

Answers (2)

SalunkeAkash
SalunkeAkash

Reputation: 256

you can try this code

<?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); 
}
?>

Upvotes: 1

LF-DevJourney
LF-DevJourney

Reputation: 28529

You can call shell command from php like this,

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

Upvotes: 0

Related Questions