How to remove recursively files in upload folder in Yii2


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

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

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

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


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




Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s