Page 1 of 1

How to delete all files and sub-folders from a folder in PHP?

Posted: Sun Jan 28, 2018 12:33 pm
by arnlweb
PHP delete all files and sub-folders from a folder older then one day, older then 3 months.

You can delete all WordPress cache folder and files using this php function.

I am using this code and works.

Code: Select all

<?php
//error_reporting(E_ALL); 
//ini_set('display_errors', 'on');

function rrmdir($dir) 
{
    if (is_dir($dir)) 
    {
        $objects = scandir($dir);
        foreach ($objects as $object) 
        {
            if ($object != "." && $object != "..") 
            {
                if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object);
                //if (filemtime($dir."/".$object) <= time()-60*60*24*120) @unlink($dir."/".$object); // older then 3 months
		//if (filemtime($dir."/".$object) <= time()-60*60*24*2) @unlink($dir."/".$object); // older than 2 days
		if (filemtime($dir."/".$object) <= time()-60*60*24*1) @unlink($dir."/".$object); // older than 1 days
		//if (filemtime($dir."/".$object) <= time()-60) @unlink($dir."/".$object); // older than 60 seconds
		echo $dir."/".$object.' <span style="color:red">> File Checked.</span><br>';

            }
        }
        reset($objects);
        rmdir($dir);
    }
}


  $docroot = $_SERVER['DOCUMENT_ROOT'];
  //echo $docroot;
  $docroot_delete = $docroot.'/wp-content/cache';
  //echo $docroot_delete;
  rrmdir($docroot_delete);
?>