How to remove recursively files in upload folder in Yii2

Hi,

The below is example of function which can be used to recursively removed files in Yii2 using the command utility.

This function checks the modification date of files and removes files older than 30 days from @app/web/upload directory.

public function actionDeleteOldAttachments()
{
$cutOfdate = time() – 3600 * 24 * 30; // only 30 days to leave
$num=0;

$pathToFiles = Yii::getAlias(‘@app’).’/web/uploads/’;
$files = glob($pathToFiles.’*’);

foreach ($files as $file) {
if(is_dir($file)){
$filesInsideDirectory = glob($file.’/*’);

foreach($filesInsideDirectory as $subfile){
if(filemtime($subfile) < $cutOfdate ){
echo “\n”.$subfile.filemtime($subfile);

unlink($subfile);

}
}
}else{
//check modification date
if(filemtime($file) < $cutOfdate ){
echo “\n”.$file.filemtime($file);

unlink($file);
}
}

}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s