Delete files in a directory older than a specific time using php

Published


Here is how you can delete all files in a folder those are older than a specific time,using php.

Change DIRECTORYNAME to the name of  directory which you want the contents to be deleted.
Copy and paste this to any text editor. save as .php file.upload to your server.

<?php
$DIR = './DIRECTORYNAME/';
if ($handle = opendir($DIR)) {

// This is the correct way to loop over the directory.
    while (false !== ($file = readdir($handle))) {
        if ( filemtime($DIR.$file) <= time()-60) {
           unlink($DIR.$file);
        }
    }

    closedir($handle);
}
else
{
echo "cannot open dir";
}
?>


Code Explained

<?php
$DIR = './DIRECTORYNAME/'; //Storing directory path to variable $DIR.
if ($handle = opendir($DIR)) { //Checks whether there is any errors,(read and write permission)-or
                                                 directory exist.
// This is the correct way to loop over the directory.
    while (false !== ($file = readdir($handle))) {//Looping over files till the last one.
        if ( filemtime($DIR.$file) <= time()-60) {//Checking  filemtime(file modified time) of each time and
                                                                    checks whether its lower or higher than the specified time,if it is
                                                                    lower ,then
           unlink($DIR.$file);//deleting the file.
        }
    }

    closedir($handle); //Closing the directory
}
else//if there is any error with folder, then-
{
echo "cannot open dir"; //Displaying the error message 'Cannot open dir'
}
?>

Function Used

unlink()

Unlink() used to remove the file.



Comments

Post a Comment