在实际项目中,经常遇到这样的需求,比如mysql备份文件删除,日志文件删除
该文章中提供三种方法来实现
删除某个目录下的三天5小时之前的后缀为txt的文件
一,shell脚本方式
0 0 * * * find /home/test -name "*.txt" -type f -cmin +4620 -exec rm {} \;
二,php方式
/*
* 删除文件夹下$time分钟前创建的文件
* crontab 添加定时任务
* @param $dir 要处理的目录,物理路径
* @param $time 过期时间 时间戳
* @return void
*/
function delFile($dir, $time){
if(is_dir($dir)){
if($dh=opendir($dir)){
while (false !== ($file = readdir($dh))){
if($file!="." && $file!=".."){
$fullpath=$dir."/".$file;
if(!is_dir($fullpath)){
$filedate=filectime($fullpath);
if ( $filedate <= $time && preg_match( "/\.txt$/i" , $fullpath )) {
unlink($fullpath); //删除文件
}
}