街道一个需求要删除半年前的图片,自己研究了一下,供大家参考 //定时删除图片 public function actionDelImg() { //获取半年前的时间 $date_year = date('Ymd', strtotime("-6 month")); $php_path = dirname(__FILE__) . '/'; $path = $php_path; if (is_dir($path)) { $this->delDirAndFile($path, $date_year); } else { $path = $php_path; if (is_dir($path)) { $this->delDirAndFile($path, $date_year); } else { exit('DONE'); } } }
//清空文件夹和文件夹 function delDirAndFile($dirName, $date_year) { if ($handle = opendir("$dirName")) { while (false != ($item = readdir($handle))) { if ($item != "." && $item != "..") { if (is_dir("$dirName/$item")) { $this->delDirAndFile("$dirName/$item", $date_year); } else { if (preg_match('/^[0-9]{14}_[0-9]{5}.(jpg|png|jpeg|gif|bmp)$/', $item)) { //如果是图片格式,并且时间在半年后 $date_img = substr($item, 0, 8); if ($date_img < $date_year) { //if (unlink("$dirName/$item")) echo '成功删除文件'.$dirName/$item; unlink("$dirName/$item"); } else { continue; } } else { continue; } } } } closedir($handle); if (!preg_match('/^.+onlinelisting$/', $dirName)) { //if (rmdir($dirName)) echo '成功删除目录'.$dirName .'<br>'; @rmdir($dirName); } } }